本文主要是介绍C# NPOI Excel固定模板写入数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
导出数据触发:
<div>
<input type="button" value="导出" onclick="ImportExcel()" />
</div>
后台实现:
//Excel模板string TempletFileName = context.Server.MapPath("..../UploadFile/test.xls");HSSFWorkbook wk = null;using (FileStream fs = File.Open(TempletFileName, FileMode.Open,FileAccess.Read, FileShare.ReadWrite)){//把xls文件读入workbook变量里,之后就可以关闭了wk = new HSSFWorkbook(fs);fs.Close();}HSSFSheet sheet1 = (HSSFSheet)wk.GetSheetAt(0);DoctorBLL bll = new DoctorBLL();DataTable exportTable = bll.GetExportQuestionTable();if (exportTable != null){int nRow = 2;string nextFirstTxt = string.Empty;for (int i = 0; i < exportTable.Rows.Count; i++){IRow row = sheet1.CreateRow(nRow);for (int j = 0; j < exportTable.Columns.Count; j++){//添加数据到excel中 row.CreateCell(j).SetCellValue(exportTable.Rows[i][j]);}nRow++;}}context.Response.ContentType = "application/vnd.ms-excel";// 添加头信息,指定文件名格式 context.Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");context.Response.AddHeader("Content-Transfer-Encoding", "binary");context.Response.ContentType = "application/octet-stream";context.Response.ContentEncoding = System.Text.Encoding.UTF8;MemoryStream file = new MemoryStream();wk.Write(file);context.Response.BinaryWrite(file.GetBuffer());
这篇关于C# NPOI Excel固定模板写入数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!