C# Export DataTable values to Excel:
- public static void InsertWorksheet(DataTable table, string docName)
- {
- try
- {
- SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(docName, SpreadsheetDocumentType.Workbook);
-
- WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
- workbookpart.Workbook = new Workbook();
-
- WorksheetPart worksheetPart = workbookpart.AddNewPart < WorksheetPart > ();
-
- worksheetPart.Worksheet = new Worksheet(new SheetData());
-
- Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild < Sheets > (new Sheets());
-
-
- Sheet sheet = new Sheet()
- {
- Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
- SheetId = 1,
- Name = “Report”
- };
- sheets.Append(sheet);
-
- SheetData sheetData = worksheetPart.Worksheet.GetFirstChild < SheetData > ();
-
-
- Row row;
- row = new Row()
- {
- RowIndex = 1
- };
- sheetData.Append(row);
- List < String > columns = new List < string > ();
-
- foreach(System.Data.DataColumn column in table.Columns)
- {
- Cell refCell = null;
- Cell newCell = new Cell();
- row.InsertBefore(newCell, refCell);
- newCell.CellValue = new CellValue(column.ColumnName);
- columns.Add(column.ColumnName);
- }
- UInt32 iIndex = 1;
-
- foreach(System.Data.DataRow dsrow in table.Rows)
- {
- Row rowdata;
- rowdata = new Row()
- {
- RowIndex = iIndex + 1
- };
- sheetData.Append(rowdata);
- foreach(String col in columns)
- {
- Cell refCell = null;
- Cell newCell = new Cell();
- rowdata.InsertBefore(newCell, refCell);
- newCell.CellValue = new CellValue(dsrow[col].ToString());
- }
- iIndex++;
- }
-
- spreadsheetDocument.Close();
- }
- catch (Exception ex)
- {}
- }