最近幫朋友做網站,有提到能不能弄一個把資料匯出成 Excel 檔的功能,剛好最近看到網路上有人分享 ClosedXML,於是寫了支小程式來測試。
專案中,用 NuGet 搜尋 ClosedXML 就能找到了。
首先定義資料的格式。
public class TestClass
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public string Field1;
public string Field2;
}
由於 ClosedXML 接受的參數是 DataTable,所以先寫一個將物件轉換為 DataTable 的功能,用基本的 Reflection 就能處理。
public static DataTable ConvertObjectsToDataTable(IEnumerable<object> objects)
{
DataTable dt = null;
if (objects != null && objects.Count() > 0)
{
Type type = objects.First().GetType();
dt = new DataTable(type.Name);
foreach (PropertyInfo property in type.GetProperties())
{
dt.Columns.Add(new DataColumn(property.Name));
}
foreach (FieldInfo field in type.GetFields())
{
dt.Columns.Add(new DataColumn(field.Name));
}
foreach (object obj in objects)
{
DataRow dr = dt.NewRow();
foreach (DataColumn column in dt.Columns)
{
PropertyInfo propertyInfo = type.GetProperty(column.ColumnName);
if (propertyInfo != null)
{
dr[column.ColumnName] = propertyInfo.GetValue(obj, null);
}
FieldInfo fieldInfo = type.GetField(column.ColumnName);
if (fieldInfo != null)
{
dr[column.ColumnName] = fieldInfo.GetValue(obj);
}
}
dt.Rows.Add(dr);
}
}
return dt;
}
接下來將 DataTable 轉換為 Excel 檔,使用上出乎意料的簡單。
public static void ExportExcelFromDataTable(DataTable dt, string fileName)
{
XLWorkbook workbook = new XLWorkbook();
workbook.AddWorksheet(dt, "Sheet1");
workbook.SaveAs(fileName);
workbook.Dispose();
}測試程式。
List<TestClass> list = new List<TestClass>();
list.Add(new TestClass { Prop1 = "p1", Prop2 = "p2", Field1 = "f1", Field2 = "f2" });
DataTable dt = ExcelUtility.ConvertObjectsToDataTable(list);
ExcelUtility.ExportExcelFromDataTable(dt, "test.xlsx");
程式碼放在 GitHub,有興趣可以參考看看。
另外,程式碼裡還包含了 ASP.NET MVC 的東西。
public ActionResult Download()
{
List<TestClass> list = new List<TestClass>();
list.Add(new TestClass { Prop1 = "p1", Prop2 = "p2", Field1 = "f1", Field2 = "f2" });
DataTable dt = ExcelUtility.ConvertObjectsToDataTable(list);
System.IO.MemoryStream stream = ExcelUtility.ExportExcelStreamFromDataTable(dt);
FileContentResult fResult = new FileContentResult(stream.ToArray(), "application/x-xlsx");
fResult.FileDownloadName = "test.xlsx";
return fResult;
}
參考資料
Dynamic Objects Conveting into Data Table in C#
文章標籤
全站熱搜
