Created
June 17, 2011 16:50
-
-
Save SamWM/1031793 to your computer and use it in GitHub Desktop.
EPPlus Worksheet Formatting (using http://epplus.codeplex.com/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text; | |
using OfficeOpenXml; | |
using OfficeOpenXml.Style; | |
using OfficeOpenXml.Table; | |
using System.Drawing; | |
using System.Data; | |
public partial class Sample: Page | |
{ | |
protected void GenerateSpreadsheet(object sender, EventArgs e) | |
{ | |
using (ExcelPackage pck = new ExcelPackage()) | |
{ | |
// date columns | |
List<string> dateColumns = new List<string>() { | |
"DateAdded", | |
"SentDate" | |
}; | |
// hide columns | |
List<string> hideColumns = new List<string>() { | |
"RecordID", | |
"CategoryID" | |
}; | |
DataTable table = GetTable(); | |
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("MyTable"); | |
ws.Cells["A1"].LoadFromDataTable(table, true, TableStyles.Medium6); | |
FormatWorksheetData(dateColumns, hideColumns, table, ws); | |
// make sure it is sent as a XLSX file | |
Response.ContentType = "application/vnd.ms-excel"; | |
// make sure it is downloaded rather than viewed in the browser window | |
Response.AddHeader("Content-disposition", "attachment; filename=myworksheet.xlsx"); | |
Response.BinaryWrite(pck.GetAsByteArray()); | |
Response.End(); | |
} | |
} | |
private DateTable GetTable() | |
{ | |
// code to retrieve data and return a DataTable | |
} | |
private static void FormatWorksheetData(List<string> dateColumns, List<string> hideColumns, DataTable table, ExcelWorksheet ws) | |
{ | |
int columnCount = table.Columns.Count; | |
int rowCount = table.Rows.Count; | |
ExcelRange r; | |
// which columns have dates in | |
for (int i = 1; i <= columnCount; i++) | |
{ | |
// if cell header value matches a date column | |
if (dateColumns.Contains(ws.Cells[1, i].Value.ToString())) | |
{ | |
r = ws.Cells[2, i, rowCount + 1, i]; | |
r.AutoFitColumns(); | |
r.Style.Numberformat.Format = @"dd MMM yyyy hh:mm"; | |
} | |
} | |
// get all data and autofit | |
r = ws.Cells[1, 1, rowCount + 1, columnCount]; | |
r.AutoFitColumns(); | |
// which columns have columns that should be hidden | |
for (int i = 1; i <= columnCount; i++) | |
{ | |
// if cell header value matches a hidden column | |
if (hideColumns.Contains(ws.Cells[1, i].Value.ToString())) | |
{ | |
ws.Column(i).Hidden = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment