C#对Excel的图文操作
1、打印Excel
目前的商业工具如水晶报表,ActiveReport等,都提供了灵活,强大的功能,但是对于比较特殊化的表格,特别是国内的一些应用,都是一个个的格子组成的,这样要是用线来一根根画就比较麻烦,但是这类工具还都不提供表格化的报表布局定义方式。一个很好的选择是VS2005的客户端报表(RDLC),但是在某几个方面还是不够灵活,例如,灵活性有限制,要想自己编码实现一些复杂逻辑还是有困难;要VS2005,对于一些还在使用VS2003的项目就只有眼馋的份了。用Excel来实现,优点在于页面布局设计灵活,同时使用代码来操作数据要更灵活,更精确。
下面是一个简单的例子,打开一个定义好的Excel文件,这个文件是作为报表的模板,然后向模板的指定格子里填充数据,形成一个报表,在web方式下可以按照指定的命名方式在服务器上生成一个excel文件,之后传送到客户端,由客户端启动excel进行打印。
Excel.Application m_objExcel = null; Excel._Workbook m_objBook = null; Excel.Sheets m_objSheets = null; Excel._Worksheet m_objSheet = null; Excel.Range m_objRange = null; object m_objOpt = System.Reflection.Missing.Value; try { m_objExcel = new Excel.Application(); m_objBook = m_objExcel.Workbooks.Open("z:\\Book1.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt); m_objSheets = (Excel.Sheets)m_objBook.Worksheets; m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1)); string[] info = new string[5] { "Cure", "26", "dahuzizyd.cnblogs.com", "汉", "按时 ?放奥斯丁奥斯丁非是否奥斯丁非" }; m_objRange = m_objSheet.get_Range("B1", m_objOpt); m_objRange.Value = info[0]; m_objRange = m_objSheet.get_Range("E1", m_objOpt); m_objRange.Value = info[1]; m_objRange = m_objSheet.get_Range("B2", m_objOpt); m_objRange.Value = info[2]; m_objRange = m_objSheet.get_Range("E2", m_objOpt); m_objRange.Value = info[3]; m_objRange = m_objSheet.get_Range("A3", m_objOpt); m_objRange.Value = info[4]; m_objExcel.DisplayAlerts = false; m_objBook.SaveAs("z:\\Book2.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { m_objBook.Close(m_objOpt, m_objOpt, m_objOpt); m_objExcel.Workbooks.Close(); m_objExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel); m_objBook = null; m_objExcel = null; GC.Collect(); }
可以看到,使用Excel要进行一部分的编码,好在这部分还不太复杂,但是最大的问题就在于当报表需求变更时,要重新编译部署,而且当格子特别多的时候,要这样硬编码还是挺痛苦的一件事。不过使用Excel毕竟给我们提供了一种选择,可以在开发时对多种方案权衡利弊,使用最适合项目的。
2、操作统计图(Chart)
下面的代码使用一个现有的统计图Excel文件,加载这个文件,设置某一项的值和统计图的表示方式,然后保存到另一个Excel文件里。如果是VS2005+Office2003,也可以选择使用Visual Studio Tools for Office来作。
Excel.Application m_objExcel = null; Excel._Workbook m_objBook = null; Excel._Chart m_objChart = null; Excel.ChartGroup m_objChartGroup = null; Excel.Series m_objSeries = null; object m_objOpt = System.Reflection.Missing.Value; try { m_objExcel = new Excel.Application(); m_objBook = m_objExcel.Workbooks.Open("z:\\Book11.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt); m_objChart = (Excel._Chart)m_objExcel.Charts.get_Item(1); m_objChart.BarShape = Excel.XlBarShape.xlCylinder; m_objChartGroup = (Excel.ChartGroup)m_objChart.ChartGroups(1); m_objSeries = (Excel.Series)m_objChartGroup.SeriesCollection(1); m_objSeries.Values = 456; m_objExcel.DisplayAlerts = false; m_objBook.SaveAs("z:\\Book2.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt, m_objOpt, m_objOpt); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { m_objBook.Close(m_objOpt, m_objOpt, m_objOpt); m_objExcel.Workbooks.Close(); m_objExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel); m_objBook = null; m_objExcel = null; GC.Collect(); this.Close(); }
源Excel文件中的统计图、经过代码处理后保存的统计图:
3、生成统计图(Chart)
有的Web项目选用Excel作为报表方案,在服务器端生成Excel文件,然后传送到客户端,由客户端进行打印。在国内的环境下,相对PDF方式,Excel的安装率应该比pdf阅读器的安装率要高,同时,微软也为C#操作Excel提供了完备的接口,虽然ZedGraph和其他的商业报表工具生成的统计图也很好,但是人家微软毕竟是大品牌,值得信赖。
本文介绍使用C#调用Excel来生成统计图(Chart)的以及Chart图中各部分控制的一些方法。
在第二小节中,我们使用一个预定义的Excel文件,通过改变Chart中的某个值来生成统计图。本文进一步演示如何从指定的数据从头生成统计图。
首先当然要添加对Excel的引用,然后需要定义几个要用到的Excel对象:
Excel.Application ThisApplication = null; Excel.Workbooks m_objBooks = null; Excel._Workbook ThisWorkbook = null; Excel.Worksheet xlSheet = null;
在创建一个新的_WorkBook对象的时候,默认的会含有3个Sheet,所以为了显示清晰,将多余的Sheet都删掉:
private void DeleteSheet() { foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets) if (ws != ThisApplication.ActiveSheet) { ws.Delete(); } foreach (Excel.Chart cht in ThisWorkbook.Charts) cht.Delete(); }
再下来需要添加用来给Chart提供数据的Sheet:
private void AddDatasheet() { xlSheet = (Excel.Worksheet)ThisWorkbook. Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet, Type.Missing, Type.Missing); xlSheet.Name = "数据"; }
生成Chart用到的数据,因为是演示,所以这里使用生成随机数的方法来替代从数据库中提取数据。
private void LoadData() { Random ran = new Random(); for (int i = 1; i <= 12; i++) { xlSheet.Cells[i, 1] = i.ToString() + "月"; xlSheet.Cells[i, 2] = ran.Next(2000).ToString(); } }
好了,到此,准备工作全部已经就绪,下面要进行Chart的生成设置部分了:
生成一个统计图对象:
Excel.Chart xlChart = (Excel.Chart)ThisWorkbook.Charts.Add(Type.Missing, xlSheet, Type.Missing, Type.Missing);
设定数据来源:
Excel.Range cellRange = (Excel.Range)xlSheet.Cells[1, 1];
通过向导生成Chart:
xlChart.ChartWizard(cellRange.CurrentRegion, Excel.XlChartType.xl3DColumn, Type.Missing, Excel.XlRowCol.xlColumns,1, 0, true , "访问量比较(dahuzizyd.cnblogs.com)", "月份", "访问量", "");
到此,Chart的生成就完成了,貌似比较简单,下面我们对其作一些设置,好更漂亮些。
设置统计图Sheet的名称:
xlChart.Name = "统计";
现在的统计图只有一个组,他们会显示成一样的颜色,我们来让12个Bar都显示不同的颜色:
Excel.ChartGroup grp = (Excel.ChartGroup)xlChart.ChartGroups(1); grp.GapWidth = 20; grp.VaryByCategories = true;
现在Chart的条目的显示形状是Box,我们让它们变成圆柱形,并给它们显示加上数据标签:
Excel.Series s = (Excel.Series)grp.SeriesCollection(1); s.BarShape = XlBarShape.xlCylinder; s.HasDataLabels = true;
下面再来设置统计图的标题和图例的显示:
xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop; xlChart.ChartTitle.Font.Size = 24; xlChart.ChartTitle.Shadow = true; xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;
最后设置两个轴的属性,Excel.XlAxisType.xlValue对应的是Y轴,Excel.XlAxisType.xlCategory对应的是X轴:
Excel.Axis valueAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue, XlAxisGroup.xlPrimary); valueAxis.AxisTitle.Orientation = -90; Excel.Axis categoryAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory, XlAxisGroup.xlPrimary); categoryAxis.AxisTitle.Font.Name = "MS UI Gothic";
到此,一切就绪了,下面要生成Chart,并将其存为一个Excel文件:
try { ThisApplication = new Excel.Application(); m_objBooks = (Excel.Workbooks)ThisApplication.Workbooks; ThisWorkbook = (Excel._Workbook)(m_objBooks.Add(Type.Missing)); ThisApplication.DisplayAlerts = false; this.DeleteSheet(); this.AddDatasheet(); this.LoadData(); CreateChart(); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); ThisApplication.Workbooks.Close(); ThisApplication.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication); ThisWorkbook = null; ThisApplication = null; GC.Collect(); this.Close(); }
运行你的程序,打开生成的Excel文件,最终生成的Chart应该像这样:
完成了Chart的生成,但是上面对于每个月只有一项数据,如果我想显示多项呢,例如显示每个月两个页面的范围量的对比。方法很简单,只要再多生成一组数据就可以了,我们修改下LoadData方法:
private void LoadData() { Random ran = new Random(); for (int i = 1; i <= 12; i++) { xlSheet.Cells[i, 1] = i.ToString() + "月"; xlSheet.Cells[i, 2] = ran.Next(2000).ToString(); xlSheet.Cells[i, 3] = ran.Next(1500).ToString(); } }
再次运行程序,生成Chart看看,应该像下面的效果:
可以看到,两组数据以不同的形状显示,同时,图例部分也不再显示1-12月共12项,而是显示两项,这是因为在上面的代码中我们设置了ChartGroup的VaryByCategories 属性:
grp.VaryByCategories = true;当我们有两个以上的组时,这一项就失效了。
在用C#操作Excel的时候,恐怕最大的困难就在于不知道Excel提供的各个对象,以及它们的属性,方法等信息,好在MSDN里有关于Excel的接口说明-Excel Primary Interop Assembly Reference,参照这些,相信很快就能上手了。
最后是完整代码:
private void button4_Click(object sender, EventArgs e) { try { ThisApplication = new Excel.Application(); m_objBooks = (Excel.Workbooks)ThisApplication.Workbooks; ThisWorkbook = (Excel._Workbook)(m_objBooks.Add(Type.Missing)); ThisApplication.DisplayAlerts = false; this.DeleteSheet(); this.AddDatasheet(); this.LoadData(); CreateChart(); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); ThisApplication.Workbooks.Close(); ThisApplication.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication); ThisWorkbook = null; ThisApplication = null; GC.Collect(); this.Close(); } } Excel.Application ThisApplication = null; Excel.Workbooks m_objBooks = null; Excel._Workbook ThisWorkbook = null; Excel.Worksheet xlSheet = null; /// <summary> /// 用生成的随机数作数据 /// </summary> private void LoadData() { Random ran = new Random(); for (int i = 1; i <= 12; i++) { xlSheet.Cells[i, 1] = i.ToString() + "月"; xlSheet.Cells[i, 2] = ran.Next(2000).ToString(); } } /// <summary> /// 删除多余的Sheet /// </summary> private void DeleteSheet() { foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets) if (ws != ThisApplication.ActiveSheet) { ws.Delete(); } foreach (Excel.Chart cht in ThisWorkbook.Charts) cht.Delete(); } /// <summary> /// 创建一个Sheet,用来存数据 /// </summary> private void AddDatasheet() { xlSheet = (Excel.Worksheet)ThisWorkbook. Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet, Type.Missing, Type.Missing); xlSheet.Name = "数据"; } /// <summary> /// 创建统计图 /// </summary> private void CreateChart() { Excel.Chart xlChart = (Excel.Chart)ThisWorkbook.Charts. Add(Type.Missing, xlSheet, Type.Missing, Type.Missing); Excel.Range cellRange = (Excel.Range)xlSheet.Cells[1, 1]; xlChart.ChartWizard(cellRange.CurrentRegion, Excel.XlChartType.xl3DColumn, Type.Missing, Excel.XlRowCol.xlColumns,1, 0, true , "访问量比较(dahuzizyd.cnblogs.com)", "月份", "访问量", ""); xlChart.Name = "统计"; Excel.ChartGroup grp = (Excel.ChartGroup)xlChart.ChartGroups(1); grp.GapWidth = 20; grp.VaryByCategories = true; Excel.Series s = (Excel.Series)grp.SeriesCollection(1); s.BarShape = XlBarShape.xlCylinder; s.HasDataLabels = true; xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop; xlChart.ChartTitle.Font.Size = 24; xlChart.ChartTitle.Shadow = true; xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous; Excel.Axis valueAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue, XlAxisGroup.xlPrimary); valueAxis.AxisTitle.Orientation = -90; Excel.Axis categoryAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory, XlAxisGroup.xlPrimary); categoryAxis.AxisTitle.Font.Name = "MS UI Gothic"; }
四、复制单元格
在用Excel作报表的时候,可能会碰到分页的情况,这样就要分成多个Sheet显示,如果要在每页都保留表头,就需要将第一页作为模板设计的表头部分拷贝到其他的Sheet上,这时就要用用到Excel中的单元格拷贝。
下面的代码说明如何一个Sheet上的选定内容拷贝到另一个Sheet上:
ThisApplication = new Excel.Application(); ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ThisApplication.DisplayAlerts = false; xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1); Excel.Range range = xlSheet.get_Range("A1", Type.Missing); range.Value = "123"; Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2); Excel.Range range1 = sheet1.get_Range("B1", Type.Missing); range.Copy(range1); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
可以看到,核心的代码是很简单的,就是选定一个源区域,然后指定另一个目标区域,调用源区域的Copy方法将内容整个复制到目标区域,但是你会发现是连单元格的格式等属性一并拷贝过去的,如果要只拷贝单元格中的文本呢?那就要用到windows剪贴板了:
xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1); Excel.Range range = xlSheet.get_Range("A1", Type.Missing); range.Value = "123"; System.Windows.Forms.Clipboard.SetDataObject(range.Value.ToString()); Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2); Excel.Range range1 = sheet1.get_Range("B1", Type.Missing); sheet1.Paste(range1, false);
要注意的是,这种方式只能选一个单元格,复制一个,不能选定一批单元格进行复制。
五、操作单元格边框和颜色、行和列
在用Excel作报表的时候,可能需要操作单元格的边框和填充颜色和纹理等操作,下面的代码说明如何设置选中的单元格的填充纹理和边框
try { ThisApplication = new Excel.Application(); ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ThisApplication.DisplayAlerts = false; xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1); Excel.Range range = xlSheet.get_Range("G4","H5"); range.Value = "123"; Excel.Style st = ThisWorkbook.Styles.Add("PropertyBorder", Type.Missing); range.Interior.Pattern = Excel.XlPattern.xlPatternCrissCross; range.Borders.Weight = 2; range.Borders.get_Item(XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous; range.Borders.get_Item(XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous; range.Borders.get_Item(XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous; range.Borders.get_Item(XlBordersIndex.xlDiagonalDown).LineStyle = Excel.XlLineStyle.xlLineStyleNone; range.Borders.get_Item(XlBordersIndex.xlDiagonalUp).LineStyle = Excel.XlLineStyle.xlLineStyleNone; range.Borders.get_Item(XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlLineStyleNone; range.Borders.get_Item(XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlLineStyleNone; range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlDot; range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).Color = System.Drawing.ColorTranslator.ToOle(Color.Red); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); ThisApplication.Workbooks.Close(); ThisApplication.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook); System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication); ThisWorkbook = null; ThisApplication = null; GC.Collect(); this.Close(); }
在Excel中,行和列实际上仍然是Range,只不过取得行和列的方法和前面几篇随笔出现的有点不同,要使用Worksheet的Rows和Columns属性的get_Item方法,下面是例子代码,演示了怎样选中行,并且在行之间复制数据,和插入行:
ThisApplication = new Excel.Application(); ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); ThisApplication.DisplayAlerts = false; xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1); //Excel.Range range = xlSheet.get_Range("G4",Type.Missing); Excel.Range range = (Excel.Range)xlSheet.Rows.get_Item(18, Type.Missing); Excel.Range range1 = (Excel.Range)xlSheet.Rows.get_Item(19, Type.Missing); range.Value = "123"; range.Copy(range1); range1.Rows.Insert(XlInsertShiftDirection.xlShiftDown); ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
六、设置chart的y坐标轴显示值[2]
使用Aspose.Cells设置chart的y坐标轴显示值。
用aspose.cell生成的chart生成的Y轴是默认生成的,自己要定义y轴坐标值
1. 把数据源写到excel里面,list里面
2.y轴坐标自己定义
第一种:默认设置:chart里面会自己定义y轴坐标
第二种:y周坐标以对数显示 chart.ValueAxis.IsLogarithmic = true; 以10 100 1000格式显示
第三种:只设置间隔值 chart.ValueAxis.MajorUnit =20000;,会自动获取y轴的最大值与最小值
第四种:设置y轴的最大值与最小值,设置间隔值
//设置y坐标轴的厚度
chart.ValueAxis.AxisLine.Weight = WeightType.WideLine;
chart.ValueAxis.Title.Text = "y轴坐标";
chart.ValueAxis.MajorUnit =20000;//设置y轴的显示值间隔
chart.ValueAxis.MaxValue = 200000;//设置y轴开始最大值
chart.ValueAxis.MinValue = 0;//设置y轴的最小值
3.设置右边坐标轴是不是显示
//设置右边坐标轴显示
chart.SecondValueAxis.IsVisible = true;
//设置y坐标轴间隔值字大小
chart.SecondValueAxis.TickLabels.Font.Size = 12;
chart.SecondValueAxis.Title.Text = "y轴坐标2";
导出效果:
//设置y坐标轴的厚度
chart.ValueAxis.AxisLine.Weight = WeightType.WideLine;
chart.ValueAxis.Title.Text = "y轴坐标";
chart.ValueAxis.MajorUnit =20000;//设置y轴的显示值间隔
chart.ValueAxis.MaxValue = 200000;//设置y轴开始最大值
chart.ValueAxis.MinValue = 0;//设置y轴的最小值
第二种:y周坐标以对数显示 chart.ValueAxis.IsLogarithmic = true; 以10 100 1000格式显示
//设置y坐标轴的厚度
chart.ValueAxis.AxisLine.Weight = WeightType.WideLine;
chart.ValueAxis.Title.Text = "y轴坐标";
chart.ValueAxis.MajorUnit =20000;//设置y轴的显示值间隔
chart.ValueAxis.MaxValue = 80000;//设置y轴开始最大值
chart.ValueAxis.MinValue = 0;//设置y轴的最小值
入口函数
public ActionResult excels() { WorkbookDesigner designer = new WorkbookDesigner(); string path = Server.MapPath("/Templete/11111.xls"); designer.Workbook.Open(path); Workbook workbook = designer.Workbook; CreateStaticData(workbook); CreateStaticReport(workbook); designer.Process(); //将流文件写到客户端流的形式写到客户端,名称是_report.xls designer.Save("_report.xls", SaveType.OpenInExcel, FileFormatType.Excel2003, System.Web.HttpContext.Current.Response); Response.Flush(); Response.Close(); designer = null; // Response.End(); return View("getexcel"); }
设置数据源
private void CreateStaticData(Workbook workbook) { //Initialize Cells object Cells cells = workbook.Worksheets[0].Cells; //Put string into a cells of Column A cells["A1"].PutValue("class"); cells["A2"].PutValue("红萝卜"); cells["A3"].PutValue("白萝卜"); cells["A4"].PutValue("青萝卜"); //Put a value into a Row 1 cells["B1"].PutValue(2002); cells["C1"].PutValue(2003); cells["D1"].PutValue(2004); cells["E1"].PutValue(2005); cells["F1"].PutValue(2006); //Put a value into a Row 2 cells["B2"].PutValue(40000); cells["C2"].PutValue(45000); cells["D2"].PutValue(50000); cells["E2"].PutValue(55000); cells["F2"].PutValue(70000); //Put a value into a Row 3 cells["B3"].PutValue(10000); cells["C3"].PutValue(25000); cells["D3"].PutValue(40000); cells["E3"].PutValue(52000); cells["F3"].PutValue(60000); //Put a value into a Row 4 cells["B4"].PutValue(5000); cells["C4"].PutValue(15000); cells["D4"].PutValue(35000); cells["E4"].PutValue(30000); cells["F4"].PutValue(20000); }
设置chart y轴的显示值
private void CreateStaticReport(Workbook workbook) { //初始化 Worksheet Worksheet sheet = workbook.Worksheets[0]; //设置 worksheet名称 sheet.Name = "Line"; //设置worksheet不显示 sheet.IsGridlinesVisible = false; //根据数据源 创建 chart int chartIndex = 0; chartIndex = sheet.Charts.Add(ChartType.Line, 5, 1, 29, 15); //初始化chart Chart chart = sheet.Charts[chartIndex]; //设置竖线不显示 chart.CategoryAxis.MajorGridLines.IsVisible = false; //设置Title样式 chart.Title.Text = "Sales By Class For Years"; chart.Title.TextFont.Color = Color.Black; chart.Title.TextFont.IsBold = true; chart.Title.TextFont.Size = 12; //设置chart的数据源 chart.NSeries.Add("B2:F4", false); chart.NSeries.CategoryData = "B1:F1"; //Set Nseries color varience to True chart.NSeries.IsColorVaried = true; //初始化 Cells Cells cells = workbook.Worksheets[0].Cells; //循环 cells for (int i = 0; i < chart.NSeries.Count; i++) { //设置系列的名称 chart.NSeries[i].Name = cells[i + 1, 0].Value.ToString(); chart.NSeries[i].MarkerStyle = ChartMarkerType.Circle; //设置系列的名称 Background 与ForeGround chart.NSeries[i].MarkerBackgroundColor = Color.Yellow; chart.NSeries[i].MarkerForegroundColor = Color.Gold; //设置系列标记 chart.NSeries[i].MarkerSize = 10; //设置Category的名称 chart.CategoryAxis.Title.Text = "Year(2002-2006)"; chart.CategoryAxis.Title.TextFont.Color = Color.Black; chart.CategoryAxis.Title.TextFont.IsBold = true; chart.CategoryAxis.Title.TextFont.Size = 10; //设置图例的位置 chart.Legend.Position = LegendPositionType.Top; } //设置y轴的样式 chart.ValueAxis.TickLabelPosition = TickLabelPositionType.NextToAxis; chart.ValueAxis.TickLabels.Font.Color = Color.Gray; chart.ValueAxis.AxisBetweenCategories = false; //chart.ValueAxis.TickLabels.Font.Size = 13; chart.ValueAxis.TickLabels.Font.IsBold = true; //Y坐标轴对数间隔展示 // chart.ValueAxis.IsLogarithmic = true; chart.ValueAxis.MajorGridLines.Color = Color.Red; chart.ValueAxis.AxisLine.Color = Color.DarkGreen; //设置y坐标轴的厚度 chart.ValueAxis.AxisLine.Weight = WeightType.WideLine; chart.ValueAxis.Title.Text = "y轴坐标"; chart.ValueAxis.MajorUnit = 20000;//MajorUnit =2000; chart.ValueAxis.MaxValue = 200000; chart.ValueAxis.MinValue = 0; //设置右边坐标轴显示 chart.SecondValueAxis.IsVisible = true; //设置y坐标轴间隔值字大小 chart.SecondValueAxis.TickLabels.Font.Size = 12; chart.SecondValueAxis.Title.Text = "y轴坐标2"; // chart.SecondValueAxis.MinorGridLines.IsVisible = true; }
7、使用EPPlus生成带图表(Chart)的Excel报表[3]
在开发.NET应用中可能会遇到需要生成带图表(Chart)的Excel报表的需求,特别是在一些ASP.NET网站中,有时候我们并不能保证 Web服务器上一定安装了Office组件,所以使用微软的Office来生成Excel并不保证在所有情况下都使用,有时候即使Web服务器上安装了 Office也会出现一些运行权限方面的原因到导致调用Excel组件生成Excel失败,所以在这里介绍一种无需安装Office并且无需较高权限就能 生成Excel的方法。
EPPlus简介
在介绍EPPlus之前,首先要介绍一下Office Open XML。以下文字来自于维基百科(网址:Office Open XML,有删节):
Office Open XML(缩写:Open XML、OpenXML或OOXML),是由Microsoft开发的一种以XML为基础并以ZIP格式压缩的电子文件,支持Word、Excel、 Office Note、PPT等文件格式。OOXML在2006年12月成为了ECMA规范的一部分,编号为ECMA-376;并于2008年4月国际标准化组织 (ISO)的表決,在两个月公布为ISO/IEC 29500国际标准。从Microsoft Office 2007开始,Office Open XML文件格式已经成为Microsoft Office默认的文件格式。Microsoft Office 2010支持对ECMA-376标准文档的读操作,ISO/IEC 29500 Transitional的读/写,ISO/IEC 29500 Strict的读取。Microsoft Office 2013同时支持ISO/IEC 29500 Strict的读写操作。
EPPlus就是一个通过Open XML方式来读写Office文件的开源.NET类库,所以使用它生成Office文件完全不需要Microsoft Office(当然如果你需需要查看生成的文件就需要Office了)。它的官方网址是:http://epplus.codeplex.com/。如果需要体验本文中提到的效果,需要从这个网址下载最新版本的类库,我现在使用的这个名为EPPlus.dll类库仅658K,非常方便部署。
代码示例
为了演示EPPlus的用法,这里写了一个简单的例子,在这个例子里演示模拟了几大公司实际业绩与计划业绩的百分比,如果这个百分比大于95%则会将所 在的单元格显示为绿色,如果小于90%则会显示为红色,否则就显示为黄色,并且还会生成一个图标来直观表示每月实际完成情况与计划的百分比。
完整代码如下:
/* ******************************************************************************** * * Project A report project * Module Name Excel Report * Author Zhou, Jin-Qiao (周金桥) * Creation Date [11/03/2013] * Description Generate Excel Report with Chat demo by Epplus * * Copyright 2013 zhoufoxcn. * ******************************************************************************** */ using System; using System.Data; using System.Drawing; using System.IO; using OfficeOpenXml; using OfficeOpenXml.Drawing.Chart; using OfficeOpenXml.Style; namespace ExcelReportApplication { /// <summary> /// 使用EPPlus生成带图表(Chart)的Excel文件的例子,注意在运行的机器上无需安装Office,因为EPPlus是使用基于OpenXML技术生成的Excel文件。 /// 任何网站和个人均可在不对本代码做任何修改的情况下转载本文及本文中示例的代码用于非商业用途,任何除去版权的行为均为侵权。 /// 作者:周公(周金桥) /// 创建日期:2013-11-03 /// 博客地址:http://blog.csdn.net/zhoufoxcn http://zhoufoxcn.blog.51cto.com /// 新浪微博地址:http://weibo.com/zhoufoxcn public class ExcelExportPage { private static readonly string[] MonthNames = new string[] { "一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"}; //private static readonly string[] CommpanyNames = new string[] { "Microsoft", "IBM", "Oracle", "Amazon", "Google", "Facebook", "Twitter", "Paypal", "Yahoo", "HP" }; private static readonly string[] CommpanyNames = new string[] { "Microsoft", "IBM", "Oracle", "Google","Yahoo", "HP" }; static void Main(string[] args) { ExcelExportPage.GenerateExcelReport(); } /// <summary> /// 周公(周金桥)说明:这个方法就是主要演示如何生成带图表(Chart)的Excel文件的例子 /// </summary> public static void GenerateExcelReport() { string fileName = "ExcelReport-"+DateTime.Now.ToString("yyyy_MM_dd_HHmmss") + ".xlsx"; string reportTitle = "2013年度五大公司实际情况与原计划的百分比"; FileInfo file = new FileInfo("C:\\"+fileName); using (ExcelPackage package = new ExcelPackage(file)) { ExcelWorksheet worksheet = null; ExcelChartSerie chartSerie = null; ExcelLineChart chart = null; #region research worksheet = package.Workbook.Worksheets.Add("Data"); DataTable dataPercent = GetDataPercent(); //chart = Worksheet.Drawings.AddChart("ColumnStackedChart", eChartType.Line) as ExcelLineChart; chart = worksheet.Drawings.AddChart("ColumnStackedChart", eChartType.LineMarkers) as ExcelLineChart;//设置图表样式 chart.Legend.Position = eLegendPosition.Right; chart.Legend.Add(); chart.Title.Text = reportTitle;//设置图表的名称 //chart.SetPosition(200, 50);//设置图表位置 chart.SetSize(800, 400);//设置图表大小 chart.ShowHiddenData = true; //chart.YAxis.MinorUnit = 1; chart.XAxis.MinorUnit = 1;//设置X轴的最小刻度 //chart.DataLabel.ShowCategory = true; chart.DataLabel.ShowPercent = true;//显示百分比 //设置月份 for (int col = 1; col <= dataPercent.Columns.Count; col++) { worksheet.Cells[1, col].Value = dataPercent.Columns[col - 1].ColumnName; } //设置数据 for (int row = 1; row <= dataPercent.Rows.Count; row++) { for (int col = 1; col <= dataPercent.Columns.Count; col++) { string strValue = dataPercent.Rows[row - 1][col - 1].ToString(); if (col == 1) { worksheet.Cells[row + 1, col].Value = strValue; } else { double realValue = double.Parse(strValue); worksheet.Cells[row + 1, col].Style.Fill.PatternType = ExcelFillStyle.Solid; worksheet.Cells[row + 1, col].Style.Numberformat.Format = "#0\\.00%";//设置数据的格式为百分比 worksheet.Cells[row + 1, col].Value = realValue; if (realValue< 0.90d)//如果小于90%则该单元格底色显示为红色 { worksheet.Cells[row + 1, col].Style.Fill.BackgroundColor.SetColor(Color.Red); } else if (realValue>= 0.90d && realValue <= 0.95d)//如果在90%与95%之间则该单元格底色显示为黄色 { worksheet.Cells[row + 1, col].Style.Fill.BackgroundColor.SetColor(Color.Yellow); } else { worksheet.Cells[row + 1, col].Style.Fill.BackgroundColor.SetColor(Color.Green);//如果大于95%则该单元格底色显示为绿色 } } } //chartSerie = chart.Series.Add(worksheet.Cells["A2:M2"], worksheet.Cells["B1:M1"]); //chartSerie.HeaderAddress = worksheet.Cells["A2"]; //chart.Series.Add()方法所需参数为:chart.Series.Add(X轴数据区,Y轴数据区) chartSerie = chart.Series.Add(worksheet.Cells[row + 1, 2, row + 1, 2 + dataPercent.Columns.Count - 2], worksheet.Cells["B1:M1"]); chartSerie.HeaderAddress = worksheet.Cells[row + 1, 1];//设置每条线的名称 } //因为假定每家公司至少完成了80%以上,所以这里设置Y轴的最小刻度为80%,这样使图表上的折线更清晰 chart.YAxis.MinValue = 0.8d; //chart.SetPosition(200, 50);//可以通过制定左上角坐标来设置图表位置 //通过指定图表左上角所在的行和列及对应偏移来指定图表位置 //这里CommpanyNames.Length + 1及3分别表示行和列 chart.SetPosition(CommpanyNames.Length + 1, 10, 3, 20); #endregion research package.Save();//保存文件 } } /// <summary> /// 生成数据,由于这一步不是主要逻辑,所以采用随机生成数据的方式,实际中可根据需要从数据库或其它数据源中读取需要的数据 /// </summary> /// <returns></returns> private static DataTable GetDataPercent() { DataTable data = new DataTable(); DataRow row = null; Random random=new Random(); data.Columns.Add(new DataColumn("公司名", typeof(string))); foreach(string monthName in MonthNames){ data.Columns.Add(new DataColumn(monthName, typeof(double))); } //每个公司每月的百分比表示完成的业绩与计划的百分比 for (int i = 0; i < CommpanyNames.Length; i++) { row = data.NewRow(); row[0] = CommpanyNames[i]; for (int j = 1; j <= MonthNames.Length; j++) { //这里采用了随机生成数据,但假定每家公司至少完成了计划的85%以上 row[j] = 0.85d + random.Next(0, 15) / 100d; } data.Rows.Add(row); } return data; } } }
最终生成的Excel文件内容如下:
参考博文
[1] The Last Day Of Summer, 将Excel应用于报表开发中, 2006-11。(本文第1~5章)
[2] 红萝卜, 使用Aspose.Cells 设置chart的y坐标轴显示值,2014-1.
[3] 周金桥, 在.NET中不安装Office使用EPPlus生成带图表(Chart)的Excel报表, 2013-11.
没有整理与归纳的知识,一文不值!高度概括与梳理的知识,才是自己真正的知识与技能。 永远不要让自己的自由、好奇、充满创造力的想法被现实的框架所束缚,让创造力自由成长吧! 多花时间,关心他(她)人,正如别人所关心你的。理想的腾飞与实现,没有别人的支持与帮助,是万万不能的。