項目中的一個功能是將數據導入到Excel文件中,這里使用NPOI操作Excel,代碼如下:
public class Excel : IDataTransfer { public Stream Export(string[] titles, List<string>[] dataSource) { return ExportData(titles, dataSource); } protected virtual Stream ExportData(string[] titles, List<string>[] dataSource) { if (dataSource == null) { throw new ArgumentNullException(); } HSSFWorkbook book = new HSSFWorkbook(); ISheet sheet = book.CreateSheet("sheet1"); int rowCount = dataSource.Length; int cellCount = dataSource[0].Count; var titleRow = sheet.CreateRow(0); #region header style // 該行的高度 titleRow.HeightInPoints = 18; // 列的樣式 ICellStyle headStyle = book.CreateCellStyle(); // 單元格內容居中顯示 headStyle.Alignment = HorizontalAlignment.Center; // 字體樣式 IFont font = book.CreateFont(); // 字體大小 font.FontHeightInPoints = 12; // 粗體 font.Boldweight = 1200; // 字體顏色 font.Color = NPOI.HSSF.Util.HSSFColor.Green.Index; headStyle.SetFont(font); // 邊框 headStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; headStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; headStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; headStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; #endregion for (int i = 0; i < titles.Length; i++) { ICell cell = titleRow.CreateCell(i); cell.SetCellValue(titles[i]); cell.CellStyle = headStyle; } for (int i = 0; i < rowCount; i++) { IRow row = sheet.CreateRow(i + 1); for (int j = 0; j < cellCount; j++) { row.CreateCell(j).SetCellValue(dataSource[i][j]); } } Stream stream = new MemoryStream(); book.Write(stream); book.Close(); stream.Position = 0; return stream; } }
Contorller中的代碼:
Excel excel = new Excel(); Stream dataStream = excel.Export(titles.ToArray(), data); return new FileStreamResult(dataStream, "application/ms-excel") { FileDownloadName = "exportInfo.xlsx" };
整個功能的實現並沒有太大難度,這里有一點需要注意就是Excel
類中的protected virtual Stream ExportData(string[] titles, List<string>[] dataSource)
方法,這個方法返回一個流,流中包含要導出的數據。方法的倒數第二行:stream.Position = 0;
,這里需要特別注意,將數據寫入流中之后,流的位置在最末端,我們要將流的位置重置到起始位置,否則無法讀取流中的數據,也就無法導出流中的數據了。