标签:
年后工作第一天,根据客户要求修善EPPLUS报表。
Epplus:
Epplus是一个使用Open Office XML(Xlsx)文件格式,能读写Excel 2007/2010文件的开源组件
好处很多,比office COM组件好用,不用考虑运营机的office版本问题。需要引用epplus.及 using OfficeOpenXml;
规范:
所有操作语句都放在以下using中:
string file = outputDir.FullName; if (File.Exists(file)) File.Delete(file); FileInfo newFile = new FileInfo(file); using (ExcelPackage xlPackage = new ExcelPackage(template, true)) { Byte[] bin = xlPackage.GetAsByteArray(); File.WriteAllBytes(file, bin); //xlPackage.Workbook.Worksheets[1] } return file;
AS-IS:模板的overview 从A5开始是做好的为模板的一部分,固定不变,现需要根据数据库内容自动更新。
TO-BE:如下,根据内容填充并自动填充公式及样式。
代码如下:
//2016-02-15新增 新增自动更新DEALER_GROUP列表的功能 #region DataTable dtOverview = mo.GetOverview(); DataRow dr = dtOverview.NewRow(); DataRow dr1 = dtOverview.NewRow(); dr[0] = ""; dr[1] = "Others"; dr[2] = "OTHERS"; dr1[0] = ""; dr1[1] = "Total"; dr1[2] = ""; dtOverview.Rows.Add(dr); dtOverview.Rows.Add(dr1); if(dtOverview.Rows.Count > 0) { ExcelWorksheet ws_Overview = xlPackage.Workbook.Worksheets["Overview"]; //填充方式 var dataRange = ws_Overview.Cells["A5"].LoadFromDataTable(dtOverview, false); //填充数据 dataRange.AutoFitColumns(); //填充公式 for (int i = 5; i < dtOverview.Rows.Count - 1 + 5; i++) { var dataRangeFormula0 = ws_Overview.Cells[i, 4]; dataRangeFormula0.Formula = "=IFERROR(SUMIFS(DCI_MO_TGT!E:E,DCI_MO_TGT!C:C,Overview!B" + i + "),\"\")"; var dataRangeFormula1 = ws_Overview.Cells[i, 5]; dataRangeFormula1.Formula = "=IFERROR(SUMIFS(DCI_MO_TGT!G:G,DCI_MO_TGT!C:C,Overview!B" + i + "),\"\")"; var dataRangeFormula9 = ws_Overview.Cells[i, 13]; dataRangeFormula9.Formula = "=SUM(J" + i + ",K" + i + ",L" + i + ")"; //... } for (int j = 4; j <= 18;j++ ) { int Row = dtOverview.Rows.Count + 5 - 1; int RowBottom = Row - 1; var dataRangeFormula = ws_Overview.Cells[Row, j]; string chr = mo.IndexToColumn(j); dataRangeFormula.Formula = "=SUM(" + chr + "5" + ":" + chr + RowBottom + ")"; } //设置样式 for (int j = 1; j <= 20; j++) { int Row = dtOverview.Rows.Count + 5 - 1; for(int i = 5;i <= Row;i++) { var dataRangeLine = ws_Overview.Cells[i, j]; dataRangeLine.Style.Border.Right.Style=OfficeOpenXml.Style.ExcelBorderStyle.Thin; dataRangeLine.Style.Border.Bottom.Style=OfficeOpenXml.Style.ExcelBorderStyle.Thin; if(i==Row) { dataRangeLine.Style.Font.Bold=true; dataRangeLine.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid; dataRangeLine.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightBlue); } } } } #endregion
很简单,主要是需要提的是一个EXCEL里:列号与字母的对应问题,因为填充公式时候一般需要的是列字母。以下是IndexToColumn(int i)方法:
public string IndexToColumn(int index) { if (index <= 0) { throw new Exception("Invalid parameter"); } index--; string column = string.Empty; do { if (column.Length > 0) { index--; } column = ((char)(index % 26 + (int)‘A‘)).ToString() + column; index = (int)((index - index % 26) / 26); } while (index > 0); return column; }
标签:
原文地址:http://www.cnblogs.com/ammy714926/p/5191779.html