特性如下:
大概說一下,整個設計吧,
1、首先有一個 IExcelExporter 的接口,第一如下:
1 public interface IExcelExporter
2 {
3 Task BuildSheetsAsync(
4 Stream stream, IEnumerable<Settings> settings_list, bool useOldVersion = false,
5 object hostContext = null);
6 }
2、然後有一個抽象類, ExcelExporterBase<TWorkBook, TWorkSheet, TCellStyle> 實現 IExcelExporter 接口。
抽象類裡面封裝了創建表頭、創建表格主題的、合並列中連續重復值 等的算法。然後定義了一些需要在子類是實現的抽象方法。如下:
1 #region [ protected ] 2 3 protected abstract TWorkBook CreateWorkBook(bool useOldVersion); 4 5 protected abstract TWorkSheet CreateWorkSheet(TWorkBook workbook, string name, Settings settings); 6 7 protected abstract TCellStyle CreateCellStyle(TWorkBook workbook, TCellStyle style, CellStyle cellStyle); 8 9 protected abstract TCellStyle GetCellStyle(TWorkBook workbook, TWorkSheet sheet, int row, int col); 10 11 protected abstract void SetCell(TWorkBook workbook, TWorkSheet sheet, int row, int col, Settings settings, ColNode node, object value, TCellStyle style, bool setValue = true, bool setStyle = true); 12 13 protected abstract void MergeCells(TWorkBook workbook, TWorkSheet sheet, int startRow, int endRow, int startCol, int endCol, Settings settings); 14 15 protected abstract void FreezePane(TWorkBook workbook, TWorkSheet sheet, int rowSplit, int colSplit); 16 17 protected abstract void SetColumnsWidth(TWorkBook workbook, TWorkSheet sheet, Settings settings, uint[] widthArray, int startCol); 18 19 protected abstract void AutoFillColumns(TWorkBook workbook, TWorkSheet sheet, Settings settings, int startCol); 20 21 protected abstract void Save(TWorkBook workbook, bool useOldVersion, Stream stream); 22 23 #endregion
幾個抽象方法,都很好理解,根據方法名很容易知道要實現的功能。
3、在具體的實現中我用 Aspose.Cells 和 NPOI 分別實現了一套。
Aspose_Cells_ExcelExporter、 NPOI_ExcelExporter 這兩個類。
4、使用示例。
DataTable dt = MAIN.Get_Users();
Settings set = new Settings()
{
PageSize = 100,
Name = "",
ColumnsAutoWidth = true,
StartColIndex = 1,
StartRowIndex = 1,
DataSource = new Lazy<System.Collections.Generic.IEnumerable<SysUser>>(() =>
{
string str = ConfigurationManager.ConnectionStrings["mysql_demo"].ConnectionString;
return MAIN.helper.ToEnumerable2<SysUser>("SELECT * FROM SysUser"); //MAIN.Get_Users();
}),
FreezeHeader = true,
//RowStyleGetter = (i, row) => i % 2 == 0 ? CellStyle.Body : new CellStyle() { BgColor = Color.White, FgColor = RandColor() },
RootNodes = new[]{
new ColNode(){
Title = "用戶列表",
ChildColNodes = dt.Columns.Cast<
DataColumn>().Select(col =>
new ColNode {
Title = col.ColumnName,
Field = col.ColumnName,
MergeField = col.ColumnName
}).ToArray()
}
}
};
IExcelExporter ep = new NPOI_ExcelExporter();
Task task = ep.BuildSheetsAsync(
new FileStream("./test.xlsx", FileMode.Create, FileAccess.Write),
new[] { set }, false);
task.Wait();
這裡導出時,我將表頭作為了一個父列,DataTable 的所有列作為子列。
比如 SysUser 表結構如下 : ID、UserName、Sex
那麼導出的 Excel 格式如下
用戶列表 ID UserName Sex
已在開源中國開源,有需要的朋友,可以下載,歡迎拍磚。