通过 NPOI 第三方插件 实现 Excel 的导出

思路:

1,将 前台 的查询条件 传入给后台,后台 通过这些查询条件 得到 DataTable dt, 

2,找到 要导出的Excel 模板,循环 dt ,并逐条将数据插入到 Excel 里面去,最后输出Excel 文件

注意: 导出的Excel 模板 必须是 xls 文件

public void ExportExcel(string templateXlsPath, DataTable dt)
{
if (File.Exists(templateXlsPath))
{
 using (FileStream file = new FileStream(templateXlsPath, FileMode.Open, FileAccess.Read))
{
 ISheet _sheetBasic = null;
 IWorkbook _excel = WorkbookFactory.Create(file);
 _sheetBasic = _excel.GetSheet("sheet1");
 file.Close();
 int index = 2;//表示从Excel中的第3行开始写入数据,第1行,和第2行 分别是 英文字段和中文字段
 if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
 IRow _row = _sheetBasic.CreateRow(index);//表示每循环一次,在Excel中创建一行,并给这一行
 string SNUMBER = dt.Rows[i]["NUMBER"].ToString();
 string BUKRS = dt.Rows[i]["BUKRS"].ToString();
 string WERKS = dt.Rows[i]["WERKS"].ToString();
 string MATNR = dt.Rows[i]["MATNR"].ToString();
 string LFGJA = dt.Rows[i]["LFGJA"].ToString();
 string LFMON = dt.Rows[i]["LFMON"].ToString();
 string PROJECT = dt.Rows[i]["PROJECT"].ToString();
 string ZVER = dt.Rows[i]["ZVER"].ToString();
 string WK1_PLAN1 = dt.Rows[i]["WK1_PLAN1"].ToString();
 string WK2_PLAN1 = dt.Rows[i]["WK2_PLAN1"].ToString();
 string WK3_PLAN1 = dt.Rows[i]["WK3_PLAN1"].ToString();
 string WK4_PLAN1 = dt.Rows[i]["WK4_PLAN1"].ToString();
 string WK5_PLAN1 = dt.Rows[i]["WK5_PLAN1"].ToString();
_row.CreateCell(0).SetCellValue(SNUMBER);
_row.CreateCell(1).SetCellValue(BUKRS);
_row.CreateCell(2).SetCellValue(WERKS);
_row.CreateCell(3).SetCellValue(MATNR);
_row.CreateCell(4).SetCellValue(LFGJA);
_row.CreateCell(5).SetCellValue(LFMON);
_row.CreateCell(6).SetCellValue(ZVER);
_row.CreateCell(7).SetCellValue(PROJECT);
_row.CreateCell(8).SetCellValue(WK1_PLAN1);
_row.CreateCell(9).SetCellValue(WK2_PLAN1);
_row.CreateCell(10).SetCellValue(WK3_PLAN1);
_row.CreateCell(11).SetCellValue(WK4_PLAN1);
_row.CreateCell(12).SetCellValue(WK5_PLAN1);
index++;
}
}
string FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
HttpContext.Response.ContentType = "application/ms-excel";
HttpContext.Response.Charset = "";
HttpContext.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Response.AppendHeader("content-disposition", "attachment;filename="" + System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
using (MemoryStream ms = new MemoryStream())
{
//将工作簿的内容放到内存流中
_excel.Write(ms);
//将内存流转换成字节数组发送到客户端
HttpContext.Response.BinaryWrite(ms.GetBuffer());
HttpContext.Response.End();
}
}
}
}

3,导出 excel 文件 或 是下载 文件:

  .net 下载文件的一种方式: 利用隐藏域框架来 实现 下载文件。

 <iframe name="hideIframe" id="hideIframe" src="" width="0" height="0" scrolling="no" frameborder="0" style="display: none"></iframe>

 //利用隐藏框架实现下载文件
 function importTemplete_onclick() {// 点击下载按钮时 调用该方法触发 下载文件

     hideIframe.location.href = "../Handler/DownTemplateHandler.ashx?Action=downFG_OutputTemplate&&temp=" + (new Date()).getTime();
}

原文地址:https://www.cnblogs.com/dlf-myDream/p/5254455.html