主要使用NPOI对word、excel、压缩包做一些流操作
目录
1、NPOI - WORD模板
1.1、替换个别值
public BaseResultModel<string> WordReplace(string vchYear, string vchMonth)
{
try
{
Dictionary<string, string> dic = new Dictionary<string, string>{
{ "@VchYear",vchYear},
{ "@VchMonth",vchMonth},
};
string templatePath = System.AppDomain.CurrentDomain.BaseDirectory + @"upload/template.docx";
string savePath = System.AppDomain.CurrentDomain.BaseDirectory + @"upload/AAA.docx";
WordTemplateHelper.WriteToPublicationOfResult(templatePath, savePath, dic);
return new SuccessResultModel<string>(savePath);
}
catch (Exception ex)
{
return new ErrorResultModel<string>(EnumErrorCode.业务执行失败, "error:" + ex.Message);
}
}
效果如图
1.2、为模板追加list
public BaseResultModel<string> ExportPayBounsPoint(string pernr = null, string year = null)
{
try
{
// 1.获取数据DataTable
DataTable dt = TeacherOrgehResultlInfoService.GetPayBounsPointByPernr(pernr, year)?.Data;
// 2.找到模板文件
string templateUrl = AppDomain.CurrentDomain.BaseDirectory + "upload/template/教师工作量津贴教分表.xlsx";
// 3.通过文件模板创建NPOIWorkBook对象,从第几行追加datatable数据源
NopiExcel.ExportExcelByTemple(dt, "", templateUrl, 0, 3);
return ...
}
catch (Exception e)
{... }
}
效果如图
2、OFFICE操作
[HttpPost]
[NoLog]
public BaseResultModel<string> OfficeAction(AcademicYearViewModel model)
{
try
{
string baseUrl = System.AppDomain.CurrentDomain.BaseDirectory;
List<DicViewModel> listResult = IDicService.ListViewPageDic(null)?.Data?.ListData?.ToList();
DataTable excelTalbe = DataTableHelper.ToDataTable<DicViewModel>(listResult);
#region 导出表头
Dictionary<string, string> dic = new Dictionary<string, string>(){
{ "UnitCode","单位编号"},
{ "UnitName","单位名称"}
};
NopiExcel.ListToExcel(dic, "Template.xls");
#endregion
#region List导出excel
dic = new Dictionary<string, string>(){
{ "AcademicYearName","学年"},
{ "Term","学期"}
};
if (listResult.Count > 0)
{
NopiExcel.ListToExcel(listResult, "AAAA.xls", dic);
}
#endregion
#region DataTable导出Excel
ExcelTableColModify(excelTalbe);
//DataTable --> 文件流
Stream sam = NopiExcel.StreamFromDataTable(excelTalbe, ".xls");
MemoryStream ms = NopiExcel.StreamToMemoryStream(sam);
NopiExcel.DownloadUploadFile(ms, "情况表", ".xls");
#endregion
#region Excel、Word 转Pdf
// 依赖于office 服务器需要安装office组件
WordToPDF(baseUrl + "upload/AAA.docx", baseUrl + "upload/template.pdf");
ExcelToPDF(baseUrl + "upload/BBB.xls", baseUrl + "upload/template1.pdf");
// 内存占用高,大文件容易溢出
PdfConverHelper.ConverToPdf(baseUrl + "upload/BBB.xls", baseUrl + "upload/template3.pdf");
PdfConverHelper.ConverToPdf(baseUrl + "upload/AAA.docx", baseUrl + "upload/template2.pdf");
#endregion
#region 常规流操作
//DataTable --> 文件流
Stream stream = NopiExcel.StreamFromDataTable(excelTalbe, ".xls");
//stream一个文件流只能使用一次 ,多次使用需拷贝流,且只能拷贝一次
//文件流 --> DataTable
DataTable dt = NopiExcel.ExcelToTable(stream, ".xls", 0, 0);
//Excel文件 --> DataTable 通过文件路径转为DataTable
DataTable dt1 = NopiExcel.ExcelToDataTable(baseUrl + @"upload/CCC.xls");
//stream --> Excel文件
NopiExcel.WriteSteamToFile(NopiExcel.StreamToMemoryStream(stream), baseUrl + @"/upload/123.xls");
#endregion
}
catch (Exception ex)
{
LogWriter.WriteLog(EnumLogLevel.Fatal, "OfficeAction", JsonConvert.SerializeObject(model), "UploadController", "操作office 发生错误.", ex);
return new ErrorResultModel<string>(EnumErrorCode.系统异常, "操作office 发生错误!");
}
return null;
}
3、WebAPI上传文件传参
前端使用fromdata传入
代码块
public BaseResultModel<string> ImportInfo(HttpRequestMessage Request)
{
HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];
// 获取Excel文件流访问权限
HttpPostedFile file = HttpContext.Current.Request.Files[0];
DataTable dt = NopiExcel.ExcelToTable(file.InputStream, ".xls", 0, 0);
string type = file.ContentType.ToLower();
if (!type.Contains("excel") && !type.Contains("sheet"))
{
return new ErrorResultModel<string> { ErrorCode = EnumErrorCode.系统异常, ErrorMessage = "暂只支持excel文件导入" };
}
string tableName = context.Request["tableName"];
}
3、MVC上传文件传参
前端使用input(multiple) + Ajax
代码块
[HttpPost]
public ActionResult AddExcelToDic()
{
try
{
HttpPostedFileBase file = Request.Files["file"];
if (file.ContentLength == 0)
{
TempData["err"] = "请选择上传文件";
}
string type = file.ContentType.ToLower();
IWorkbook workbook = new XSSFWorkbook(file.InputStream);
......
}
}