NPOI導出Excel文件的文章很多了,但是沒看到easy-ui datagrid表格直接導出Excel文件的,要顯示中文Title和Excel文件每列列寬和頁面上看到的基本相符。這里可能是個實現,不是最佳,寫出來給有用的人參考。可能在通用二字上做得還不是特別好,有好的方法請留言指正。
效果:
編碼過程:
1、js
//----------------------------------------------------- // @description 返回grid的(可見的)所有行給后端導出Excel用 // @param {string} table 表格ID // @returns rows // @author 肖峰 //------------------------------------------------------ function getGridDataToExcelExport(table) { var allRows = $("#" + table).datagrid("getRows"); return allRows; } //----------------------------------------------------- // @description 返回grid的所有列 // @param {string} table 表格ID // @returns rows // @author 肖峰 function getGridColumnFields(table) { var allCols = $("#" + table).datagrid("getColumnFields"); return allCols; } //----------------------------------------------------- // @description 返回grid的所有列的選項title、列寬等 // @param {string} table 表格ID // @returns rows // @author 肖峰 function getGridColumnFieldsOptions(table) { var allColsTitle = $("#" + table).datagrid("options").columns; return allColsTitle; } //導出結果集到Excel function exportGrid() { if (getGridDataToExcelExport("ResultGrid").length == 0) { alertMsg("系統提示", "記錄數為0,不需要導出!", "error"); return; } var entity = {}; entity.GridRows = getGridDataToExcelExport("ResultGrid"); entity.GridColumnOptions = getGridColumnFieldsOptions("ResultGrid"); entity.ExportFileName = '產品箱盒對應查詢結果.xls'; POVOS.BarCode.Website.BoxCorrespondingQuery.ExportGridToExcelFileAndDownload(entity, function (p) { location.href = "ExportExcelFile.ashx?ExcelFileID=" + p.value; }); } //導出結果集到Excel function exportGrid() { if (getGridDataToExcelExport("ResultGrid").length == 0) { alertMsg("系統提示", "記錄數為0,不需要導出!", "error"); return; } var entity = {}; entity.GridRows = getGridDataToExcelExport("ResultGrid"); entity.GridColumnOptions = getGridColumnFieldsOptions("ResultGrid"); entity.ExportFileName = '產品物流流向查詢結果.xls'; POVOS.BarCode.Website.ProductTransQuery.ExportGridToExcelFileAndDownload(entity, function (p) { location.href = "ExportExcelFile.ashx?ExcelFileID="+p.value; }); }
2、后台代碼,前台使用ajaxpro2調用后台方法,傳遞前端頁面grid行列記錄的Json格式。
/// <summary> /// 形成Excel對應的文件流存在數據庫里,返回給前端File GUID /// </summary> /// <param name="entity"></param> /// <returns></returns> [AjaxMethod] public string ExportGridToExcelFileAndDownload(JavaScriptObject entity) { var gridRows = (JavaScriptArray)entity["GridRows"]; var gridOptions = (JavaScriptArray)entity["GridColumnOptions"]; var gridOptionList = (JavaScriptArray)gridOptions[0]; //可見的列 List<JavaScriptObject> gridCols = new List<JavaScriptObject>(); foreach (JavaScriptObject j in gridOptionList) { if (j.Value.IndexOf("hidden") == -1) { gridCols.Add(j); } } var fileName = entity["ExportFileName"].ToString(); string tempFileName = AppDomain.CurrentDomain.BaseDirectory + "CommonExcelFile.xls"; FileStream fs = new FileStream(tempFileName, FileMode.Open, FileAccess.Read); var workBook = new HSSFWorkbook(fs); workBook.SetSheetName(0,"查詢結果"); var sheet = workBook.GetSheetAt(0); //表頭(列),第一行 int newColIndex = 0; var titleRow = sheet.CreateRow(newColIndex); int cIndex = 0; foreach (JavaScriptObject j in gridCols) { titleRow.CreateCell(cIndex).SetCellValue(j["title"].ToString()); int width = int.Parse(j["width"].ToString()) / 6; if (width > 255) width = 250; sheet.SetColumnWidth(cIndex, width*256); cIndex++; } //行記錄 for (int rowIndex = 0; rowIndex < gridRows.Count; rowIndex++) { newColIndex++; var row = sheet.CreateRow(newColIndex); var jsonEntity = gridRows[rowIndex] as JavaScriptObject; for (int colIndex = 0; colIndex < gridCols.Count; colIndex++) { string cellValue = string.Empty; JavaScriptObject colOption = (JavaScriptObject)gridCols[colIndex]; string field = colOption["field"].ToString(); if (jsonEntity[field] != null) cellValue = jsonEntity[field].ToString(); row.CreateCell(colIndex).SetCellValue(cellValue); } } MemoryStream newFile = new MemoryStream(); sheet.Workbook.Write(newFile); using (POVOSEntities db = new POVOSEntities()) { var resultFile = new ExportFileEntity(); resultFile.FileGuid = Guid.NewGuid(); resultFile.FileName = fileName; resultFile.FileCreateDateTime = DateTime.Now; resultFile.FileStreamByte = newFile.GetBuffer(); db.AddToExportFileEntity(resultFile); db.SaveChanges(); return resultFile.FileGuid.ToString(); } }
3、文件下載使用一般處理程序,接收QueryString里傳的文件ID,返回給前端Excel文件。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using BarCode.DataAccess; namespace POVOS.BarCode.Website { /// <summary> /// 讀取數據庫Excel文件並下載 /// </summary> public class ExportExcelFile : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { using (POVOSEntities db = new POVOSEntities()) { Guid fileID = new Guid(context.Request["ExcelFileID"] as string); var fileEntity = db.ExportFileEntity.Where(e => e.FileGuid == fileID).FirstOrDefault(); string filename = string.Format("[{0}]{1}", DateTime.Now.ToString("yyMMddHHmmss"), fileEntity.FileName); context.Response.ContentType = "application/vnd.ms-excel"; context.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", context.Server.UrlEncode(filename))); context.Response.Clear(); context.Response.BinaryWrite(fileEntity.FileStreamByte); context.Response.End(); } } public bool IsReusable { get { return false; } } } }
總結一下,遇到以下幾個問題:
1、如何傳遞datagrid的行列記錄到后置代碼里,形成Excel文件。
2、NPOI的使用,如果控制列寬,對齊樣式等。
3、下載時文件名顯示為亂碼。
4、解析前端頁面傳遞過來的JSON,比如某些列沒有"hidden"選項等。