Skip to content

Instantly share code, notes, and snippets.

@tocalai
Last active May 27, 2021 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tocalai/16e188c622ae307869b52476d9e95d7f to your computer and use it in GitHub Desktop.
Save tocalai/16e188c622ae307869b52476d9e95d7f to your computer and use it in GitHub Desktop.
Demonstrate how to export excel and format datetime column(s) style for human readable.
public static class ExcelExtension {
public static FileInfo Export<T> (string filepath, List<T> data) {
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
var output = new FileInfo (filepath);
if (output.Exists) output.Delete ();
if (!Directory.Exists (Path.GetDirectoryName (filepath))) Directory.CreateDirectory (Path.GetDirectoryName (filepath));
using (var excel = new ExcelPackage (output)) {
var ws = excel.Workbook.Worksheets.Add ("Sheet1"); // create sheet
var rows = data.Count + 1;
if (rows > 0) {
ws.Cells[1, 1].LoadFromCollection (data, true, TableStyles.Medium16); // write data include header
}
var indexs = FindDateTimeColumns (data.FirstOrDefault ()).ToList ();
indexs.ForEach (i => {
ws.Column (++i).Style.Numberformat.Format = "MM/dd/yyyy hh:mm:ss AM/PM"; // assign datetime style
});
ws.Cells.AutoFitColumns (); // fit the content width
excel.Save (); // save all content
}
return output;
// find out datatime column(s)'s correspond index, so we could force assign the style on its
static IEnumerable<int> FindDateTimeColumns<T> (T obj) {
var indexs = obj.GetType ()
.GetProperties ()
.Select ((item, index) => new { Item = item, Index = index })
.Where (o => o.Item.PropertyType == typeof (DateTime))
.Select (o => o.Index);
return indexs;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment