Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public ActionResult ExportToExcel()
- {
- ViewBag.CurrentUser = getCurrentUser();
- var projects = (from u in getDB().ProjectsSet
- select u).ToList();
- // Load Excel application
- Application excel = new Application();
- // Create empty workbook
- excel.Workbooks.Add();
- //Workbook wb = new Workbook();
- // Create Worksheet from active sheet
- _Worksheet workSheet = excel.ActiveSheet;
- // I created Application and Worksheet objects before try/catch,
- // so that i can close them in finnaly block.
- // It’s IMPORTANT to release these COM objects!!
- try
- {
- // ————————————————
- // Creation of header cells
- // ————————————————
- workSheet.Cells[1, "A"] = "Id";
- workSheet.Cells[1, "B"] = "Name";
- workSheet.Cells[1, "C"] = "Fast Track";
- // ————————————————
- // Populate sheet with some real data from ” Studentts” list
- // ————————————————
- int row = 2; // start row (in row 1 are header cells)
- foreach (Projects projet in projects)
- {
- workSheet.Cells[row, "A"] = projet.Id;
- workSheet.Cells[row, "B"] = projet.Name;
- workSheet.Cells[row, "C"] = projet.FastTrack;
- row++;
- }
- // Apply some predefined styles for data to look nicely ??
- workSheet.Range["A1"].AutoFormat(Microsoft.Office.Interop.Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic1);
- //Autofit cells
- for(int y = 1; y == 25; y++)
- {
- workSheet.Columns[y].AutoFit();
- }
- // Define filename
- string test = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
- string fileName = string.Format(@"{0}ProjectsExport_as_of_" + DateTime.Now.ToShortDateString() + ".xlsx", Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory));
- // Save this data as a filestring fileName = "C:\ProjectsExport_as_of_"+DateTime.Now.ToShortDateString()+".xlsx";
- workSheet.SaveAs(fileName);
- return File(fileName, "application/vnd.ms-excel", "ProjectsExport_as_of_" + DateTime.Now.ToShortDateString() + ".xlsx");
- }
- catch (Exception exception)
- {
- Console.Write(exception.InnerException);
- return null;
- }
- finally
- {
- // Quit Excel application
- excel.Quit();
- // Release COM objects (very important!)
- if (excel != null)
- System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
- if (workSheet != null)
- System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
- // Empty variables
- excel = null;
- workSheet = null;
- // Force garbage collector cleaning
- GC.Collect();
- }
Add Comment
Please, Sign In to add comment