Export to Excel (.xlsx) using Open xml in C#

Dear readers, This post is about implementing and reusing the Export to Excel functionality using Open XML. Following the steps given below will guide you through the same. Every methods are supported by the comments for better understanding. Do write for clarifications, if any. 1) Add the below Class, “ExportToExcelUtility” to the project where you need to implement the functionality. (in the presentation layer).

public sealed class ExportToExcelUtility

{

/// <summary>

/// Convert the list to Data table.

/// </summary>

/// <param name=”items”>List</param>

/// <returns>DataTable</returns>

public static DataTable ToDataTable<T>(List<T> items)

{

DataTable dataTable = new DataTable(typeof(T).Name);

PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

foreach (PropertyInfo prop in Props)

{

dataTable.Columns.Add(prop.Name);//Setting column names

}

foreach (T item in items)

{

var values = new object[Props.Length];

for (int i = 0; i < Props.Length; i++)

{

values[i] = Props[i].GetValue(item, null);//Insert values.

}

dataTable.Rows.Add(values);

}

return dataTable;

}

/// <summary>

/// Call this method from the Page providing the desired information

/// </summary>

/// <param name=”dataTable”>The records to be written in excel</param>

/// <param name=”excelFilename”>Name of the file</param>

/// <param name=”sheetName”>Name of the sheet</param>

/// <param name=”filters”>Search key and value based on which the datatable is generated</param>

/// <param name=”columnSize”>column name and size</param>

/// <returns></returns>

public static bool CreateExcelDocument(DataTable dataTable, string excelFilename, string sheetName, Dictionary<string, string> filters, Dictionary<string,   int> columnSize)

{

try

{

using (SpreadsheetDocument objExcelDoc = SpreadsheetDocument.Create(excelFilename, SpreadsheetDocumentType.Workbook))

{

int cellSize;

WorkbookPart wbp = objExcelDoc.AddWorkbookPart();

WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();

Workbook wb = new Workbook();

FileVersion fv = new FileVersion();

fv.ApplicationName = “Microsoft Office Excel”;

Worksheet workSheet = new Worksheet();

WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();

wbsp.Stylesheet = CreateStylesheet();

wbsp.Stylesheet.Save();

Columns columns = new Columns();

for (int i = 1; i <= columnSize.Count(); i++)

{

columnSize.TryGetValue(columnSize.Keys.ElementAt(i – 1).ToString(), out cellSize);

columns.Append(CreateColumnData(Convert.ToUInt32(i), Convert.ToUInt32(i), cellSize));

}

workSheet.Append(columns);

SheetData sheetData = new SheetData();

for (UInt32 i = 2; i <= 1 + filters.Count(); i++)

{

sheetData.Append(CreateFilters(i, filters));

}

sheetData.Append(CreateColumnHeader(Convert.ToUInt32(filters.Count() + 3), columnSize));

UInt32 index = Convert.ToUInt32(filters.Count() + 4);

foreach (DataRow dr in dataTable.Rows)

{

sheetData.Append(CreateContent(index, dr, columnSize.Count()));

index++;

}

workSheet.Append(sheetData);

wsp.Worksheet = workSheet;

Sheets sheets = new Sheets();

Sheet sheet = new Sheet();

sheet.Name = sheetName;

sheet.SheetId = 1;

sheet.Id = wbp.GetIdOfPart(wsp);

sheets.Append(sheet);

wb.Append(fv);

wb.Append(sheets);

objExcelDoc.WorkbookPart.Workbook = wb;

objExcelDoc.WorkbookPart.Workbook.Save();

objExcelDoc.Close();

}

}

catch (Exception ex)

{

throw;

}

return true;

}

/// <summary>

/// Create column for storing data by passing the start column index, end column index and column width

/// </summary>

/// <param name=”StartColumnIndex”>start column index</param>

/// <param name=”EndColumnIndex”>end column index</param>

/// <param name=”ColumnWidth”>width of each column</param>

/// <returns>column</returns>

private static Column CreateColumnData(UInt32 StartColumnIndex, UInt32 EndColumnIndex, double ColumnWidth)

{

Column column;

column = new Column();

column.Min = StartColumnIndex;

column.Max = EndColumnIndex;

column.Width = ColumnWidth;

column.CustomWidth = true;

return column;

}

/// <summary>

/// Writes the row to the excel by reading each datarow from the datatable

/// </summary>

/// <param name=”index”>row index</param>

/// <param name=”dr”>data row</param>

/// <param name=”columns”>number of columns</param>

/// <returns></returns>

private static Row CreateContent(UInt32 index, DataRow dr, int columns)

{

Row objRow = new Row();

Cell objCell;

try

{

objRow.RowIndex = index;

for (int i = 65; i < 65 + columns; i++)

{

objCell = new Cell();

objCell.StyleIndex = 5;

objCell.DataType = CellValues.String;

objCell.CellReference = (char)i + index.ToString();

objCell.CellValue = new CellValue(dr.ItemArray[i – 65].ToString());

objRow.Append(objCell);

}

}

catch (Exception ex)

{

throw;

}

return objRow;

}

/// <summary>

/// Defines the Style sheet for the excel.

/// </summary>

/// <returns>Stylesheet</returns>

private static Stylesheet CreateStylesheet()

{

Stylesheet ss = new Stylesheet();

Fonts fts = new Fonts();

DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();

FontName ftn = new FontName();

ftn.Val = StringValue.FromString(“Calibri”);

DocumentFormat.OpenXml.Spreadsheet.FontSize ftsz = new DocumentFormat.OpenXml.Spreadsheet.FontSize();

ftsz.Val = DoubleValue.FromDouble(11);

ft.FontName = ftn;

ft.FontSize = ftsz;

fts.Append(ft);

ft = new DocumentFormat.OpenXml.Spreadsheet.Font();

ftn = new FontName();

ftn.Val = StringValue.FromString(“Palatino Linotype”);

ftsz = new DocumentFormat.OpenXml.Spreadsheet.FontSize();

ftsz.Val = DoubleValue.FromDouble(18);

ft.FontName = ftn;

ft.FontSize = ftsz;

fts.Append(ft);

fts.Count = UInt32Value.FromUInt32((uint)fts.ChildElements.Count);

Fills fills = new Fills();

Fill fill;

PatternFill patternFill;

fill = new Fill();

patternFill = new PatternFill();

patternFill.PatternType = PatternValues.None;

fill.PatternFill = patternFill;

fills.Append(fill);

fill = new Fill();

patternFill = new PatternFill();

patternFill.PatternType = PatternValues.Gray125;

fill.PatternFill = patternFill;

fills.Append(fill);

fill = new Fill();

patternFill = new PatternFill();

patternFill.PatternType = PatternValues.Solid;

patternFill.ForegroundColor = new ForegroundColor();

patternFill.ForegroundColor.Rgb = HexBinaryValue.FromString(“CDCDCD”);

patternFill.BackgroundColor = new BackgroundColor();

patternFill.BackgroundColor.Rgb = patternFill.ForegroundColor.Rgb;

fill.PatternFill = patternFill;

fills.Append(fill);

fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);

Borders borders = new Borders();

Border border = new Border();

border.LeftBorder = new LeftBorder();

border.RightBorder = new RightBorder();

border.TopBorder = new TopBorder();

border.BottomBorder = new BottomBorder();

border.DiagonalBorder = new DiagonalBorder();

borders.Append(border);

border = new Border();

border.LeftBorder = new LeftBorder();

border.LeftBorder.Style = BorderStyleValues.Thin;

border.RightBorder = new RightBorder();

border.RightBorder.Style = BorderStyleValues.Thin;

border.TopBorder = new TopBorder();

border.TopBorder.Style = BorderStyleValues.Thin;

border.BottomBorder = new BottomBorder();

border.BottomBorder.Style = BorderStyleValues.Thin;

border.DiagonalBorder = new DiagonalBorder();

borders.Append(border);

borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);

CellStyleFormats csfs = new CellStyleFormats();

CellFormat cf = new CellFormat();

cf.NumberFormatId = 0;

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 0;

csfs.Append(cf);

csfs.Count = UInt32Value.FromUInt32((uint)csfs.ChildElements.Count);

uint iExcelIndex = 164;

NumberingFormats nfs = new NumberingFormats();

CellFormats cfs = new CellFormats();

NumberingFormat nfForcedText = new NumberingFormat();

nfForcedText.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);

nfForcedText.FormatCode = StringValue.FromString(“@”);

nfs.Append(nfForcedText);

cf = new CellFormat();

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 0;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 1;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 0;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.NumberFormatId = nfForcedText.NumberFormatId;

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 0;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.NumberFormatId = nfForcedText.NumberFormatId;

cf.FontId = 1;

cf.FillId = 0;

cf.BorderId = 0;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.FontId = 0;

cf.FillId = 0;

cf.BorderId = 1;

cf.FormatId = 0;

cfs.Append(cf);

cf = new CellFormat();

cf.FontId = 0;

cf.FillId = 2;

cf.BorderId = 1;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

cf = new CellFormat();

cf.NumberFormatId = nfForcedText.NumberFormatId;

cf.FontId = 0;

cf.FillId = 2;

cf.BorderId = 1;

cf.FormatId = 0;

cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);

cfs.Append(cf);

ss.Append(nfs);

ss.Append(fts);

ss.Append(fills);

ss.Append(borders);

ss.Append(csfs);

ss.Append(cfs);

CellStyles css = new CellStyles();

CellStyle cs = new CellStyle();

cs.Name = StringValue.FromString(“Normal”);

cs.FormatId = 0;

cs.BuiltinId = 0;

css.Append(cs);

css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);

ss.Append(css);

DifferentialFormats dfs = new DifferentialFormats();

dfs.Count = 0;

ss.Append(dfs);

TableStyles tss = new TableStyles();

tss.Count = 0;

tss.DefaultTableStyle = StringValue.FromString(“TableStyleMedium9”);

tss.DefaultPivotStyle = StringValue.FromString(“PivotStyleLight16”);

ss.Append(tss);

return ss;

}

/// <summary>

/// Create the header row provided with the row index and header list with each column size

/// </summary>

/// <param name=”index”>row index</param>

/// <param name=”headerList”>header name and column width</param>

/// <returns></returns>

private static Row CreateColumnHeader(UInt32 index, Dictionary<string, int> headerList)

{

Row objRow = new Row();

objRow.RowIndex = index;

Cell objCell;

for (int i = 0; i < headerList.Count(); i++)

{

objCell = new Cell();

objCell.DataType = CellValues.String;

objCell.StyleIndex = 6;

objCell.CellReference = Convert.ToChar(65 + i) + index.ToString();

objCell.CellValue = new CellValue(headerList.Keys.ElementAt(i).ToString());

objRow.Append(objCell);

}

return objRow;

}

/// <summary>

/// Creating the filters based on which data row is generated. For creating header templates

/// </summary>

/// <param name=”index”>Row index</param>

/// <param name=”filters”>Search key and its respective value</param>

/// <returns></returns>

private static Row CreateFilters(UInt32 index, Dictionary<string, string> filters)

{

Row objRow = new Row();

try

{

objRow.RowIndex = index;

Cell objcell;

objcell = new Cell();

objcell.DataType = CellValues.String;

objcell.StyleIndex = 6;

objcell.CellReference = “A” + index.ToString();

objcell.CellValue = new CellValue(filters.Keys.ElementAt(Convert.ToInt32(index – 2)).ToString());

objRow.Append(objcell);

objcell = new Cell();

objcell.DataType = CellValues.String;

objcell.StyleIndex = 5;

objcell.CellReference = “B” + index.ToString();

objcell.CellValue = new CellValue(Convert.ToString(filters.ElementAt(Convert.ToInt32(index – 2)).Value));

objRow.Append(objcell);

}

catch (Exception ex)

{

throw;

}

return objRow;

}

}

2) Add the following namespaces to the page where you need to implement export to excel functionality

using System.Web.UI;

using System.Web.UI.WebControls;

using DocumentFormat.OpenXml.Spreadsheet;

using DocumentFormat.OpenXml;

using System.Data;

using DocumentFormat.OpenXml.Packaging;

using System.Reflection;

using System.IO;

3) In the event that requires to perform export to excel, call the CreateExcelDocument by providing the datatable generated, filename, sheetname, search filters as key value pair, column names and each column size as key value pairs.

protected void btnExportToExcel_Click(object sender, ImageClickEventArgs e)

{

try

{

Dictionary<string, string> filters = new Dictionary<string, string>();

//filters.Add(“Search Key”,”Search Value”); to add the filters for generating the template rows

Dictionary<string, int> Columns = new Dictionary<string, int>();

//Columns.Add(“Column name”,size in integer); to add the column name and its respective size

DataTable DataList = new DataTable();

DataList = ExportToExcelUtility.ToDataTable(call the method that returns The list to be written in Excel);

string date = DateTime.Now.ToString(“ddMMMyyHHmmtt”);

string filename = System.IO.Path.GetTempPath() + (Session[“FileName”].ToString()) + DateTime.Now.ToString(“ddMMMyyHHmmtt”) + “.xlsx”;

if (ExportToExcelUtility.CreateExcelDocument(DataList, filename, date, filters, Columns))

{

Response.ClearContent();

FileStream objFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);

byte[] data1 = new byte[objFileStream.Length];

objFileStream.Read(data1, 0, data1.Length);

Response.ContentType = “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”;

Response.AddHeader(“Content-Disposition”, string.Format(“attachment; filename={0}”, filename));

Response.BinaryWrite(data1);

}

}

catch (Exception ex)

{

}

Response.End();

}

Note: Make sure you have added open xml dll to the project. The open xml dll can be downloaded from https://docs.google.com/file/d/0B915XE_zbo18d0xudGVzYW11dXc/edit?usp=sharing

Happy Learning Folks!!!

Advertisements

6 responses to “Export to Excel (.xlsx) using Open xml in C#

  1. Hi thanks for the code, however the xlsx file open gave an error – Excel found unreadable content in Do you want to recover the contents of the workbook…and gave me an empty file 😦 Please suggest/help

  2. Hi thanks for that implementation. But I’m using an IDictionnary instead of a List and I can’t convert it to DataTable, I need to get the dictionnary keys list first. Can you suggest me an idea to do this please ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s