Guest User

Untitled

a guest
Nov 13th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. public ActionResult ExportToExcel()
  2. {
  3. ViewBag.CurrentUser = getCurrentUser();
  4. var projects = (from u in getDB().ProjectsSet
  5. select u).ToList();
  6. // Load Excel application
  7. Application excel = new Application();
  8. // Create empty workbook
  9. excel.Workbooks.Add();
  10.  
  11. //Workbook wb = new Workbook();
  12.  
  13. // Create Worksheet from active sheet
  14. _Worksheet workSheet = excel.ActiveSheet;
  15. // I created Application and Worksheet objects before try/catch,
  16. // so that i can close them in finnaly block.
  17. // It’s IMPORTANT to release these COM objects!!
  18. try
  19. {
  20. // ————————————————
  21. // Creation of header cells
  22. // ————————————————
  23. workSheet.Cells[1, "A"] = "Id";
  24. workSheet.Cells[1, "B"] = "Name";
  25. workSheet.Cells[1, "C"] = "Fast Track";
  26.  
  27. // ————————————————
  28. // Populate sheet with some real data from ” Studentts” list
  29. // ————————————————
  30. int row = 2; // start row (in row 1 are header cells)
  31. foreach (Projects projet in projects)
  32. {
  33. workSheet.Cells[row, "A"] = projet.Id;
  34. workSheet.Cells[row, "B"] = projet.Name;
  35. workSheet.Cells[row, "C"] = projet.FastTrack;
  36. row++;
  37. }
  38. // Apply some predefined styles for data to look nicely ??
  39. workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);
  40. //Autofit cells
  41. for(int y = 1; y == 25; y++)
  42. {
  43. workSheet.Columns[y].AutoFit();
  44. }
  45. // Define filename
  46. string test = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  47. string fileName = string.Format(@"{0}ProjectsExport_as_of_" + DateTime.Now.ToShortDateString() + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
  48. // Save this data as a filestring fileName = "C:\ProjectsExport_as_of_"+DateTime.Now.ToShortDateString()+".xlsx";
  49. workSheet.SaveAs(fileName);
  50.  
  51. return File(fileName, "application/vnd.ms-excel", "ProjectsExport_as_of_" + DateTime.Now.ToShortDateString() + ".xlsx");
  52.  
  53. }
  54. catch (Exception exception)
  55. {
  56. Console.Write(exception.InnerException);
  57. return null;
  58. }
  59. finally
  60. {
  61. // Quit Excel application
  62. excel.Quit();
  63. // Release COM objects (very important!)
  64. if (excel != null)
  65. System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
  66. if (workSheet != null)
  67. System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
  68. // Empty variables
  69. excel = null;
  70. workSheet = null;
  71. // Force garbage collector cleaning
  72. GC.Collect();
  73. }
Add Comment
Please, Sign In to add comment