NPOI 写download Excel 功能
Posted Aaron_M
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NPOI 写download Excel 功能相关的知识,希望对你有一定的参考价值。
1.后台代码
public Object DownloadToExcel(JObject searchCriteria, JObject validCriteria) { Dictionary<string, object> returnData = (Dictionary<string, object>)this.InitData(searchCriteria); Object dObject = this.InitData(searchCriteria); DataTable dt = ((DataSet)returnData["data"]).Tables[0]; String template = AppDomain.CurrentDomain.BaseDirectory + System.Configuration.ConfigurationSettings.AppSettings["ReportsExcelPath"] + "Template\\test123.xlsx"; IWorkbook iworkbook; using (FileStream file = new FileStream(template, FileMode.Open, FileAccess.Read)) { iworkbook = new XSSFWorkbook(file); file.Close(); } var parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(searchCriteria.ToString()); ISheet sheet1 = iworkbook.GetSheetAt(0); ICell TitleMsg = sheet1.GetRow(0).GetCell(0); IRow sourceRow = sheet1.GetRow(6); IRow headsourceRow = sheet1.GetRow(4); int i = 6, j; DateTime currentTime = DateTime.Now; TitleMsg.SetCellValue(string.Format("on:{0},{1} {2} {3} {4}", currentTime.DayOfWeek.ToString(), currentTime.Day, strMonth[currentTime.Month], currentTime.Year.ToString(), currentTime.TimeOfDay.ToString().Substring(0, 8))); //int headIndex = 4; IRow headerRow = sheet1.GetRow(3); ICell Region = sheet1.GetRow(4).GetCell(2); Region.SetCellValue(parameters["RegionText"].ToString()); foreach (DataRow row in dt.Rows) { IRow irow = sheet1.CreateRow(i); j = 0; foreach (DataColumn column in dt.Columns) { String value = row[dt.Columns[j].ColumnName].ToString(); ICell icell = irow.CreateCell(j); icell.CellStyle = sourceRow.Cells[0].CellStyle; icell.SetCellValue(value); j++; } i++; } String filename = "newfile" + DateTime.Now.ToString("yyyyMMMdd_HHmmss") + ".xlsx"; String fullpath = AppDomain.CurrentDomain.BaseDirectory + "Document\\Reports\\Output\\" + filename; FileStream files = new FileStream(fullpath, FileMode.Create); iworkbook.Write(files); files.Close(); returnData.Add("filename", "Document\\Reports\\Output\\" + filename); if (File.Exists(fullpath)) { return returnData; } else { return null; } }
2.前台使用Angular.js获取生成的表格并抛出浏览器提示:
vm.downloadToExcel = function () { var promise = webapi.post("DownloadService", "DownloadToExcel", { "searchCriteria": vm.searchParamters, "validCriteria": vm.criteria }); promise.then( function (data) { vm.filePath = data.data.filename; if (vm.filePath != "") { window.location.href = vm.filePath; } }, function (data) { logger.error("error"); }); };
以上是关于NPOI 写download Excel 功能的主要内容,如果未能解决你的问题,请参考以下文章
NPOI写Excel,Microsoft.Office.Interop.excel.dll 转换Excel为PDF