Friday, November 27, 2015

Export DataTable to Excel with Open XML in c#


This code sample will illustrate how we can create Excel file from a data table in c#.
You will need to add DocumentFormat.OpenXml and WindowsBase dll references to make it work.
private static void WriteExcelFile(string outputPath, DataTable table)
{
 using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileToGenerate, SpreadsheetDocumentType.Workbook))
 {
  WorkbookPart workbookPart = document.AddWorkbookPart();
  workbookPart.Workbook = new Workbook();

  WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
  var sheetData = new SheetData();
  worksheetPart.Worksheet = new Worksheet(sheetData);

  Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
  Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

  sheets.Append(sheet);

  Row headerRow = new Row();

  List<String> columns = new List<string>();
  foreach (System.Data.DataColumn column in table.Columns)
  {
   columns.Add(column.ColumnName);

   Cell cell = new Cell();
   cell.DataType = CellValues.String;
   cell.CellValue = new CellValue(column.ColumnName);
   headerRow.AppendChild(cell);
  }

  sheetData.AppendChild(headerRow);

  foreach (DataRow dsrow in table.Rows)
  {
   Row newRow = new Row();
   foreach (String col in columns)
   {
    Cell cell = new Cell();
    cell.DataType = CellValues.String;
    cell.CellValue = new CellValue(dsrow[col].ToString());
    newRow.AppendChild(cell);
   }

   sheetData.AppendChild(newRow);
  }

  workbookPart.Workbook.Save();
 }
}

Related Posts:

  • Deleting Features from SharePoint In one of my previous article I discussed about creating and deploying custom features to SharePoint server. Here I’m going to describe how you can r… Read More
  • SharePoint List C# Part 1 Here I'm going to show you how you can use the SharePoint object model to read sharepoint list using C#. To do this in your custom webpart or feat… Read More
  • SharePoint List C# Part 2 In my previous post SharePoint List C# Part 1, I wrote how to retrieve data from SharePoint list. In this post also I'm going to show you how to retr… Read More
  • SharePoint Web Part Development Tutorial It is hard to find out simple way to create SharePoint web parts with visual designing. After looking at custom features, in this article I'm going t… Read More
  • SharePoint User GroupsCheck User Group in SharePoint To store and manage permissions we can create User Groups in SharePoint. In this article I’ll discuss how you can che… Read More

1 comment:

  1. Thank you, it worked perfectly. Could you please advice how can we format the exported data as Table? (this would automatically show the filters for columns)

    ReplyDelete