xls 使用HSSFWorkbook
xlsx使用XSSFWorkbook
但是我使用XSSFWorkbook时没找到nuget包,引用不了,只能重新找办法,幸好workbook解决了我这个问题
/// <summary>
/// 在已有的Excel模板进行操作
/// </summary>
/// <returns></returns>
public ActionResult DownTemplate()
{
var list = departmentService.GetList();//数据源
string filepath = "/Content/Templates/XX.xlsx";
filepath = Server.MapPath(filepath);
Workbook workbook = null;
FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read);
using (file)
{
workbook = new Workbook(file);
}
var deparmenttSheet = workbook.Worksheets[];
deparmenttSheet.Cells["A1"].PutValue(new HSSFRichTextString("序号"));
deparmenttSheet.Cells["B1"].PutValue(new HSSFRichTextString("部门编码"));
deparmenttSheet.Cells["C1"].PutValue(new HSSFRichTextString("部门名称"));
for (int i = ; i < list.Count; i++)
{
var item = i + ;
deparmenttSheet.Cells["A"+item].PutValue(i+);
deparmenttSheet.Cells["B"+item].PutValue(list[i].DepartmentCode);
deparmenttSheet.Cells["C"+item].PutValue(list[i].DepartmentName);
}
//写入到表格
workbook.Save(filepath);
// 防IE文件名乱码
var fileName = HttpUtility.UrlEncode("某某信息.xlsx", System.Text.Encoding.UTF8);
HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
return File("/Content/Templates/XX.xlsx", fileName);
}
请求方法
直接使用超链接请求后台地址
<a href="/XX/DownTemplate" >下载某某信息模版</a>
这样下载后的文件名称就是“某某信息.xlsx”