大家好,又见面了,我是你们的朋友全栈君。
C#使用NPOI 导出Excel
首先需要添加NPOI的引用
//创建Excel文件的对象
HSSFWorkbook book = new HSSFWorkbook();
//添加一个sheet
IRow row2 = sheet1.CreateRow(0);
row2.CreateCell(0).SetCellValue("序号");
row2.CreateCell(1).SetCellValue("作业许可单号");
row2.CreateCell(2).SetCellValue("申请人");
row2.CreateCell(3).SetCellValue("申请单位");
row2.CreateCell(4).SetCellValue("作业日期(起)");
row2.CreateCell(5).SetCellValue("作业日期(讫)");
row2.CreateCell(6).SetCellValue("主承揽商");
row2.CreateCell(7).SetCellValue("次承揽商");
row2.CreateCell(8).SetCellValue("工作内容");
row2.CreateCell(9).SetCellValue("工作人员");
row2.CreateCell(10).SetCellValue("人数(仅供参考)");
if (list != null && list.Count > 0)
{
for (var i = 0; i < list.Count; i++)
{
IRow rowtemp2 = sheet1.CreateRow(i + 1);
//非表头
rowtemp2.CreateCell(0).SetCellValue(i + 1);//序号
rowtemp2.CreateCell(1).SetCellValue(list[i].ApplyNo);
rowtemp2.CreateCell(2).SetCellValue(list[i].ApplyInfo);
rowtemp2.CreateCell(3).SetCellValue(list[i].ApplyDept);
rowtemp2.CreateCell(4).SetCellValue(list[i].oper_from_dt.Substring(0, 10));
rowtemp2.CreateCell(5).SetCellValue(list[i].oper_to_dt.Substring(0, 10));
rowtemp2.CreateCell(6).SetCellValue(list[i].guard_name);
rowtemp2.CreateCell(7).SetCellValue(list[i].guard_send_name);
rowtemp2.CreateCell(8).SetCellValue(list[i].oper_content);
var guardWorker=list[i].GuardWorker.TrimStart(',').TrimEnd(',');
rowtemp2.CreateCell(9).SetCellValue(guardWorker);
rowtemp2.CreateCell(10).SetCellValue(Split(guardWorker).Length);
}
}
MemoryStream ms = new MemoryStream();
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
- 当为Webform项目时
//输出Excel
string filename = "紧急入场统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", Server.UrlEncode(filename)));
Response.BinaryWrite(ms.GetBuffer());
Response.Flush();
Response.End();
- 当为MVC项目时
MemoryStream ms = new MemoryStream();
book.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", survey.Name + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".xls");
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/150144.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...