Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 25th, 2012  |  syntax: None  |  size: 3.57 KB  |  hits: 29  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How to export excel from dataset or datatable in c#?
  2. using Excel = Microsoft.Office.Interop.Excel;
  3.  public static bool ExportDataTableToExcel(DataTable dt, string filepath)
  4.     {
  5.  
  6.     Excel.Application oXL;
  7.     Excel.Workbook oWB;
  8.     Excel.Worksheet oSheet;
  9.     Excel.Range oRange;
  10.  
  11.     try
  12.     {
  13.         // Start Excel and get Application object.
  14.         oXL = new Excel.Application();
  15.  
  16.         // Set some properties
  17.         oXL.Visible = true;
  18.         oXL.DisplayAlerts = false;
  19.  
  20.         // Get a new workbook.
  21.         oWB = oXL.Workbooks.Add(Missing.Value);
  22.  
  23.         // Get the Active sheet
  24.         oSheet = (Excel.Worksheet)oWB.ActiveSheet;
  25.         oSheet.Name = "Data";
  26.  
  27.         int rowCount = 1;
  28.         foreach (DataRow dr in dt.Rows)
  29.         {
  30.             rowCount += 1;
  31.             for (int i = 1; i < dt.Columns.Count + 1; i++)
  32.             {
  33.                 // Add the header the first time through
  34.                 if (rowCount == 2)
  35.                 {
  36.                     oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
  37.                 }
  38.                 oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
  39.             }
  40.         }
  41.  
  42.         // Resize the columns
  43.         oRange = oSheet.get_Range(oSheet.Cells[1, 1],
  44.                       oSheet.Cells[rowCount, dt.Columns.Count]);
  45.         oRange.EntireColumn.AutoFit();
  46.  
  47.         // Save the sheet and close
  48.         oSheet = null;
  49.         oRange = null;
  50.         oWB.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal,
  51.             Missing.Value, Missing.Value, Missing.Value, Missing.Value,
  52.             Excel.XlSaveAsAccessMode.xlExclusive,
  53.             Missing.Value, Missing.Value, Missing.Value,
  54.             Missing.Value, Missing.Value);
  55.         oWB.Close(Missing.Value, Missing.Value, Missing.Value);
  56.         oWB = null;
  57.         oXL.Quit();
  58.     }
  59.     catch
  60.     {
  61.         throw;
  62.     }
  63.     finally
  64.     {
  65.         // Clean up
  66.         // NOTE: When in release mode, this does the trick
  67.         GC.WaitForPendingFinalizers();
  68.         GC.Collect();
  69.         GC.WaitForPendingFinalizers();
  70.         GC.Collect();
  71.     }
  72.  
  73.     return true;
  74. }
  75.        
  76. private void DumpExcel(DataTable tbl)
  77. {
  78.     using (ExcelPackage pck = new ExcelPackage())
  79.     {
  80.             //Create the worksheet
  81.             ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
  82.  
  83.             //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
  84.             ws.Cells["A1"].LoadFromDataTable(tbl, true);
  85.  
  86.             //Format the header for column 1-3
  87.             using (ExcelRange rng = ws.Cells["A1:C1"])
  88.             {
  89.                 rng.Style.Font.Bold = true;
  90.                 rng.Style.Fill.PatternType = ExcelFillStyle.Solid;                      //Set Pattern for the background to Solid
  91.                 rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
  92.                 rng.Style.Font.Color.SetColor(Color.White);
  93.             }
  94.  
  95.             //Example how to Format Column 1 as numeric
  96.             using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
  97.             {
  98.                     col.Style.Numberformat.Format = "#,##0.00";
  99.                     col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
  100.                 }
  101.  
  102.                 //Write it back to the client
  103.                 Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  104.                 Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
  105.                 Response.BinaryWrite(pck.GetAsByteArray());
  106.             }
  107.         }
  108.     }
  109. }
  110.        
  111. using Microsoft.Office.Interop.Excel;