三层+MVC导出Excel(2)
背景:
出门在外,一切以健康为主,学习为辅,健康搞好了,学习也不能拉下,在外工作期间,我们在做数据导出的时候,自己封了一个类,利用NPOI进行数据导出Excel,自我感觉良好,特给大家分享一下,希望对大家的工作能有所帮助。
开发环境:
VS2012 + Sql Service + Oracle + Starteam(TFS)
框架介绍:
三层 + MVC4
业务介绍:
保密,会用到数据处理导出。我们需要做数据模板,也就是一张固定格式的excel,从这张excel上面把一些固定的东西(一些解释、映射算法)复制到另一张目标excel上面,进行数据导出
应用介绍:
1、引用NPOI
<span style="font-size:18px;">using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util;</span>
2、数据导出公共类代码分享:
<span style="font-size:18px;">/// <summary> /// 读取模板写入数据到sheet2并覆盖源文件(带sheet3的模板) /// </summary> /// <param name="cell_Title">数据集头部描述</param> /// <param name="dt_model">数据集</param> /// <param name="sheetName">Excel文件名称</param> /// <param name="rows">行数</param> /// <param name="isColumnWriten">已成功写入?</param> /// <returns></returns> publicintDataTableToExcel(string[] cellTitle,DataTabledt_model,string sheetName,int rows,bool isColumnWriten) { int count = 0; HSSFSheet sheet1 = null; //初始化Excel sheet1工作簿 HSSFSheet sheet2 = null; //初始化Excel sheet2工作簿 HSSFWorkbook wk = null; using (fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) //给新 //建excel文件赋名称,赋读写权限 { wk = new HSSFWorkbook(fs); fs.Close(); try { if (wk != null) { sheet1 = (HSSFSheet)wk.GetSheetAt(0); sheet2 = (HSSFSheet)wk.GetSheet(sheetName); } else return -1; if (isColumnWriten == true) { IRow row = sheet2.CreateRow(rows); for (int i = 0; i < cell_Title.Length; i++) { row.CreateCell(i).SetCellValue(cell_Title[i]); } count = 1; } else { count = 0; } for (int i = 0; i < dt_model.Rows.Count; i++) { IRow row = sheet2.CreateRow(count + rows); for (int j = 0; j < dt_model.Columns.Count; j++) { bool result_dou = Regex.IsMatch(dt_model.Rows[i][j].ToString(), @"^[+-]?\d*[.]?\d*$"); bool result_int = Regex.IsMatch(dt_model.Rows[i][j].ToString(), @"^[+-]?\d*$"); if (result_dou && dt_model.Rows[i][j] != DBNull.Value && dt_model.Rows[i][j] != "") row.CreateCell(j).SetCellValue(Convert.ToDouble(dt_model.Rows[i][j])); else if(result_int && dt_model.Rows[i][j] != DBNull.Value && dt_model.Rows[i][j] != "") row.CreateCell(j).SetCellValue(Convert.ToInt32(dt_model.Rows[i][j])); else row.CreateCell(j).SetCellValue(dt_model.Rows[i][j].ToString()); } count++; } sheet1.ForceFormulaRecalculation = true; using (FileStream fsm = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { wk.Write(fsm); fsm.Close(); } return count; }catch (Exception) { return -1; } } }</span>
3、Controller调用工具类进行数据导出
<span style="font-size:18px;"> bool result = true; try { for (int i = 0; i < StrFieldName.Length; i++) { if (PrintReportsBC.ReportResult(StrFieldName[i]) > 0) { DataSet ds = SelectBC.Select(StrFieldName[i].ToString(), starTime, endTime); DataTable dt = ds.Tables[0]; HSSExcelHelper hss = new HSSExcelHelper(destFileName); hss.DataTableToExcel(null, dt, sheetName, area[i], isCreateTitle); } } return result; } catch (Exception e) { return false; }</span>
4、成功导出