// 调用
ToExcel_ByTemplate(model.MainList, Server.MapPath("~/template/" + "模板表" + ".xlsx"), Server.MapPath("~/download/" + "目标表" + ".xlsx"));
//List<T> data需要导出的数据列表 fileTemplate模板地址 feedbackFileName将要导出的地址
public static void ToExcel_ByTemplate(List<T> data, string fileTemplate, string feedbackFileName)
{
int j = 0;
System.IO.FileStream file = new System.IO.FileStream(fileTemplate, FileMode.Open, FileAccess.Read);
XSSFWorkbook hssfworkbook = new XSSFWorkbook(file);
XSSFSheet ws = hssfworkbook.GetSheet("Sheet1") as XSSFSheet;//将数据导入到给定的sheet中
if (data != null && data.Count>0)
{
for (int i = 0; i < data.Count; i++)
{
j++;
IRow row = ws.CreateRow(j);
//根据模板填充数据
row.CreateCell(0).SetCellValue(data[i].data1);
row.CreateCell(1).SetCellValue(data[i].data2);
row.CreateCell(2).SetCellValue(data[i].data3);
}
}
using (FileStream filess = File.OpenWrite(feedbackFileName))
{
hssfworkbook.Write(filess);
}
}
#region 下载文件
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filepath">现在的文件相对路径</param>
/// <param name="newfilename">另存为文件的路径</param>
public void DownloadFile(string filepath, string newfilename)
{
System.IO.FileInfo filet = new System.IO.FileInfo(Server.MapPath(filepath));
Response.Clear();
Response.Buffer = true;
Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
//string newfilename1 = HttpUtility.UrlEncode(Encoding.UTF8.GetBytes(newfilename));
//Response.AddHeader("Content-Disposition", "attachment; filename=" + newfilename1);
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(newfilename));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", filet.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(filet.FullName);
// 停止页面的执行
//Response.End();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
#endregion