1. 前言 這是我最近項目剛要的需求,然後在網上找了半天的教材 但是很不幸,有關於Epplus的介紹真的太少了,然後經過了我的不斷研究然後不斷的採坑,知道現在看到Excel都想吐的時候,終於成功的完成了公司的要求,最後我 稍微的優化了一下代碼(畢竟是個剛工作一年多的新人),現在就給大家看一看不足之處 ...
1. 前言
這是我最近項目剛要的需求,然後在網上找了半天的教材 但是很不幸,有關於Epplus的介紹真的太少了,然後經過了我的不斷研究然後不斷的採坑,知道現在看到Excel都想吐的時候,終於成功的完成了公司的要求,最後我 稍微的優化了一下代碼(畢竟是個剛工作一年多的新人),現在就給大家看一看不足之處,希望給為大佬給以指點,稍後在後面我會給出項目下載。
//首頁執行 DataTable dt = DBhelper.gettable(); List<RangeData> rlist=new List<RangeData>(); RangeData rd = new RangeData(); rd.Charttype = "ColumnStacked"; rd.Yaxis = "E6,G6,O6"; rd.UserName = "測試名稱"; rd.Region = "測試地址"; rd.ChartName = "測試名稱"; rd.ChartKeyword = "F36"; rd.Appointedtime = DateTime.Now.ToString(); rlist.Add(rd); RangeData rd1 = new RangeData(); rd1.Charttype = "ColumnClustered"; rd1.Yaxis = "E6,G6,O6"; rd1.UserName = "測試名稱1"; rd1.Region = "測試地址1"; rd1.ChartName = "測試名稱1"; rd1.ChartKeyword = "F36"; rd1.Appointedtime = DateTime.Now.ToString(); rlist.Add(rd1); RangeData rd2 = new RangeData(); rd2.Charttype = "Pie"; rd2.Yaxis = "E6,G6,O6"; rd2.UserName = "測試名稱2"; rd2.Region = "測試地址2"; rd2.ChartName = "測試名稱2"; rd2.ChartKeyword = "F36"; rd2.Appointedtime = DateTime.Now.ToString(); rlist.Add(rd2); RangeData rd3 = new RangeData(); rd3.Charttype = "singleColumnClustered"; rd3.Yaxis = "E6,G6,O6"; rd3.UserName = "測試名稱23"; rd3.Region = "測試地址23"; rd3.ChartName = "測試名稱3"; rd3.ChartKeyword = "F36"; rd3.Appointedtime = DateTime.Now.ToString(); rlist.Add(rd3); ExcelInfo.ExportClient("", dt, rlist);
public class ExcelInfo
{
/// <summary> /// 輸出Excel文件 /// </summary> /// <param name="FileName"></param> /// <param name="table"></param> /// <param name="?"></param> public static void ExportClient(string FileName, DataTable table, List<RangeData> Rlist) { //reportTitle = "Microsoft,IBM,Oracle,Google.Yahoo"; FileName = FileName+DateTime.Now.ToString("yyyy_MM_dd_HHmmss") + ".xlsx"; // string TJcell = "D6,F6,H6,AJ6"; if (Directory.Exists("UpFiles")) { } else { DirectoryInfo directoryInfo = new DirectoryInfo("UpFiles"); directoryInfo.Create(); } FileInfo file = new FileInfo(@"D:\文檔資料\自學項目\EpplusExcelChartWeb\EpplusExcelChartWeb\upfiles\" + FileName); createExcel(file, table, Rlist); } /// <summary> /// 創建Excel Sheet /// </summary> /// <param name="file"></param> public static void createExcel(FileInfo file, DataTable table, List<RangeData> Rlist) { ExcelPackage package = new ExcelPackage(new FileStream(@"D:\文檔資料\自學項目\EpplusExcelChartWeb\EpplusExcelChartWeb\test1.xlsx", FileMode.Open)); ExcelWorksheet sheet = null; sheet = package.Workbook.Worksheets[1]; #region 設置Excel數據 SheetData(table, sheet); #endregion //設置圖形 if (Rlist.Count > 0) { ExcelWorksheet sheet1 = null; sheet1 = package.Workbook.Worksheets.Add("Data"); for (int i = 0; i < Rlist.Count; i++) { SheetData(table, sheet1); sheet.Cells["C3"].Value = Rlist[i].UserName; sheet.Cells["C4"].Value = Rlist[i].Region; sheet.Cells["O4"].Value = Rlist[i].Appointedtime; if (Rlist[i].Charttype == "ColumnStacked") { //堆積柱形圖 ColumnStacked(table, sheet, Rlist[i].Yaxis, Rlist[i].ChartName,Rlist[i].ChartKeyword); } else if (Rlist[i].Charttype == "ColumnClustered") { //簇狀柱形圖 ColumnClustered(table, sheet, Rlist[i].Yaxis, Rlist[i].ChartName, Rlist[i].ChartKeyword); } else if (Rlist[i].Charttype == "Pie") { //餅圖 Pie(table, sheet, Rlist[i].Yaxis, Rlist[i].ChartName, Rlist[i].ChartKeyword); } else if (Rlist[i].Charttype == "singleColumnClustered") { singleColumnClustered(table, sheet, Rlist[i].Yaxis, Rlist[i].ChartName, Rlist[i].ChartKeyword); } } } else { System.Web.HttpContext.Current.Response.Write("<script language=javascript>alert('沒有數據')</script>"); } package.SaveAs(file);//保存文件 } //工作簿數據 private static void SheetData(DataTable table, ExcelWorksheet sheet) { //if (cols[0] != "") //{ // //設置列標題 // for (int col = 1; col <= cols.Length; col++) // { // sheet.Cells[1, col].Value = cols[col - 1]; // } //} //else //{ //設置列標題 //for (int col = 1; col <= table.Columns.Count; col++) //{ // sheet.Cells[1, col].Value = table.Columns[col - 1].ColumnName; //} //} //設置數據 for (int row = 0; row < table.Rows.Count; row++) { for (int col = 0; col < table.Columns.Count; col++) { string range = sheet.MergedCells[row + 7, col + 2]; string strvalue = table.Rows[row][col].ToString(); // sheet.Cells[row + 1, col].Style.Numberformat.Format = "#0\\.00%";//設置數據的格式為百分比 if (table.Rows[row]["F36"].ToString() != "") { sheet.Cells[row + 7, col + 2].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[row + 7, col + 2].Style.Fill.BackgroundColor.SetColor(Color.Gray); sheet.Cells[row + 7, col + 2].Value = strvalue; } sheet.Cells[row + 7, col + 2].Value = strvalue; } } } /// <summary> /// 堆積柱形圖 /// </summary> private static void ColumnStacked(DataTable table,ExcelWorksheet sheet, string TJCell,string Chartname,string ChartKeyword) { ////圖表系列 ExcelChartSerie chartSerie = null; //圖表 ExcelChart chart = null; chart = sheet.Drawings.AddChart(Chartname, eChartType.ColumnStacked); chart.Legend.Position = eLegendPosition.Right; chart.Legend.Add(); chart.SetSize(500, 400);//設置圖表大小 chart.ShowHiddenData = true; #region 規定單元格生成圖表 string[] TJcellarray = TJCell.Split(','); string XAxis = string.Empty; string YAxis = string.Empty; for (int row = 1; row <= table.Rows.Count; row++) { if (table.Rows[row - 1][ChartKeyword].ToString() != "") { for (int j = 0; j < TJcellarray.Length; j++) { XAxis += "Data!" + GetEXcelstr(TJcellarray[j]) + (row + 6) + ","; YAxis += "test!" + TJcellarray[j] + ","; } int Xlength = XAxis.Length; int Ylength = YAxis.Length; XAxis = XAxis.Substring(0, Xlength - 1); YAxis = YAxis.Substring(0, Ylength - 1); chartSerie = chart.Series.Add(XAxis, YAxis); chartSerie.HeaderAddress = sheet.Cells[row + 6, 2];//設置每條線的名稱 XAxis = ""; YAxis = ""; } } #endregion // chartSerie = ChartData(table, cell, sheet, chartSerie, chart, TJcell,"F36"); chart.SetPosition(table.Rows.Count + 7, 10, 1, 20);//設置圖表位置 } /// <summary> /// 多條簇狀柱形圖 /// </summary> private static void ColumnClustered(DataTable table, ExcelWorksheet sheet, string TJCell, string Chartname, string ChartKeyword) { ////圖表系列 ExcelChartSerie chartSerie = null; //圖表 ExcelChart chart = null; chart = sheet.Drawings.AddChart(Chartname, eChartType.ColumnClustered); chart.Legend.Position = eLegendPosition.Right; chart.Legend.Add(); chart.SetSize(500, 400);//設置圖表大小 chart.ShowHiddenData = true; #region 規定單元格生成圖表 string[] TJcellarray = TJCell.Split(','); string XAxis = string.Empty; string YAxis = string.Empty; for (int row = 1; row <= table.Rows.Count; row++) { if (table.Rows[row - 1][ChartKeyword].ToString() != "") { for (int j = 0; j < TJcellarray.Length; j++) { XAxis += "Data!" + GetEXcelstr(TJcellarray[j]) + (row + 6) + ","; YAxis += "test!" + TJcellarray[j] + ","; } int Xlength = XAxis.Length; int Ylength = YAxis.Length; XAxis = XAxis.Substring(0, Xlength - 1); YAxis = YAxis.Substring(0, Ylength - 1); chartSerie = chart.Series.Add(XAxis, YAxis); chartSerie.HeaderAddress = sheet.Cells[row + 6, 2];//設置每條線的名稱 XAxis = ""; YAxis = ""; } } #endregion // chartSerie = ChartData(table, cell, sheet, chartSerie, chart, TJcell,"F36"); chart.SetPosition(table.Rows.Count + 7, 10, 10, 20);//設置圖表位置 } /// <summary> ///餅圖 /// </summary> private static void Pie(DataTable table, ExcelWorksheet sheet, string TJCell, string Chartname, string ChartKeyword) { ////圖表系列 ExcelChartSerie chartSerie = null; //圖表 ExcelChart chart = null; chart = sheet.Drawings.AddChart(Chartname, eChartType.Pie); chart.Legend.Position = eLegendPosition.Right; chart.Legend.Add(); chart.SetSize(500, 400);//設置圖表大小 chart.ShowHiddenData = true; #region 規定單元格生成圖表 string[] TJcellarray = TJCell.Split(','); string XAxis = string.Empty; string YAxis = string.Empty; for (int row = 1; row <= table.Rows.Count; row++) { if (table.Rows[row - 1][ChartKeyword].ToString() != "") { for (int j = 0; j < TJcellarray.Length; j++) { XAxis += "Data!" + GetEXcelstr(TJcellarray[j]) + (row + 6) + ","; YAxis += "test!" + TJcellarray[j] + ","; } int Xlength = XAxis.Length; int Ylength = YAxis.Length; XAxis = XAxis.Substring(0, Xlength - 1); YAxis = YAxis.Substring(0, Ylength - 1); chartSerie = chart.Series.Add(XAxis, YAxis); chartSerie.HeaderAddress = sheet.Cells[row + 6, 2];//設置每條線的名稱 XAxis = ""; YAxis = ""; } } #endregion // chartSerie = ChartData(table, cell, sheet, chartSerie, chart, TJcell,"F36"); chart.SetPosition(table.Rows.Count + 7+25, 10, 1, 20);//設置圖表位置 } /// <summary> /// 單條簇狀柱形圖 /// </summary> private static void singleColumnClustered(DataTable table, ExcelWorksheet sheet, string TJCell, string Chartname, string ChartKeyword) { ////圖表系列 ExcelChartSerie chartSerie = null; //圖表 ExcelChart chart = null; chart = sheet.Drawings.AddChart(Chartname, eChartType.ColumnClustered); chart.Legend.Position = eLegendPosition.Right; chart.Legend.Add(); chart.SetSize(500, 400);//設置圖表大小 chart.ShowHiddenData = true; #region 規定單元格生成圖表 string[] TJcellarray = TJCell.Split(','); string XAxis = string.Empty; string YAxis = string.Empty; for (int row = 1; row <= table.Rows.Count; row++) { if (table.Rows[row - 1][ChartKeyword].ToString() != "") { for (int j = 0; j < TJcellarray.Length; j++) { XAxis += "Data!" + GetEXcelstr(TJcellarray[j]) + (row + 6) + ","; YAxis += "test!" + TJcellarray[j] + ","; } int Xlength = XAxis.Length; int Ylength = YAxis.Length; XAxis = XAxis.Substring(0, Xlength - 1); YAxis = YAxis.Substring(0, Ylength - 1); chartSerie = chart.Series.Add(XAxis, YAxis); chartSerie.HeaderAddress = sheet.Cells[row + 6, 2];//設置每條線的名稱 XAxis = ""; YAxis = ""; } } #endregion // chartSerie = ChartData(table, cell, sheet, chartSerie, chart, TJcell,"F36"); chart.SetPosition(table.Rows.Count + 7 + 25, 10, 10, 20);//設置圖表位置 } /// <summary> /// 提取字元串 /// </summary> /// <param name="p_str"></param> /// <returns></returns> public static string GetEXcelstr(string p_str) { string strReturn = string.Empty; if (p_str == null || p_str.Trim() == "") { strReturn = ""; } foreach (char chrTemp in p_str) { if (!Char.IsNumber(chrTemp)) { strReturn += chrTemp; } } return strReturn; }
}
//RangeData類 public class RangeData { ///// <param name="XStartCell">數據開始單元格</param> //public string XStartCell { get; set; } // /// <param name="XEndCell">數據結束單元格</param> //public string XEndCell { get; set; } // /// <param name="EduName">Y開始單元格</param> //public string YStartCell { get; set; } // /// <param name="EduName">Y結束單元格</param> //public string YEndCell { get; set; } //圖表類型 1.ColumnStacked 堆積柱形圖 2.ColumnClustered 多條簇狀柱形圖 3.Pie餅圖4.singleColumnClustered 單條簇狀圖 public string Charttype { get; set; } //指定Y軸分類標簽 public string Yaxis { get; set; } //用戶名 public string UserName { get; set; } //所在區域 public string Region { get; set; } //指定時間 public string Appointedtime { get; set; } //圖表名稱 public string ChartName { get; set; } //製圖關鍵字 public string ChartKeyword { get; set; } }
如果執行報錯 可能是獲取Excel文件地址的問題。
下載地址https://files.cnblogs.com/files/Cjb8973/EpplusExcelChartWeb.rar