项目生成的Excel格式如下
每一部分要对应一个图表,行数与列数都是不固定的
数据用jxl生成,但jxl不能生成图表,有人说apache的poi HSSF可以,但没找到相关的demo.
jxell(http://www.jxcell.net .)好像可以,但收费
还有一种方法就是生成图片文件,然后插入到excel中,但我觉得太麻烦了
最后用vba编写了个宏来创建图表,缺点就是用户需要启用宏才能看到图
这里贴出代码以防下次忘记
'创建图表 Sub createChart() '对象的个数,即图中系列的数目 'object_length = Sheets("chart").A1 object_length = Worksheets("chart").Cells(1, 1).Value '共有多少天的数据 date_length = Worksheets("chart").Cells(1, 2).Value '有多少个kpi,即有多少个图 kpi_length = Worksheets("chart").Cells(1, 3).Value '数据源开始的行号 tmp_int = 3 For i = 1 To kpi_length Charts.Add ActiveChart.ChartType = xlLineMarkers ActiveChart.Name = "chart" & i '循环增加图 For j = 1 To object_length ActiveChart.SeriesCollection.NewSeries v = (tmp_int + date_length - 1) ActiveChart.SeriesCollection(j).XValues = "=data!R" & tmp_int & "C1:R" & v & "C1" ActiveChart.SeriesCollection(j).Values = "=data!R" & tmp_int & "C" & (j + 1) & ":R" & v & "C" & (j + 1) ActiveChart.SeriesCollection(j).Name = "=data!R" & (tmp_int - 1) & "C" & (j + 1) ActiveChart.Location Where:=xlLocationAsObject, Name:="chart" With ActiveChart .HasTitle = True .ChartTitle.Characters.Text = Worksheets("data").Cells(tmp_int - 2, 2).Value .Axes(xlCategory, xlPrimary).HasTitle = False .Axes(xlValue, xlPrimary).HasTitle = False End With Next j tmp_int = tmp_int + date_length + 4 '设置图表的位置 Set oChtObj = Worksheets("chart").ChartObjects(i) With oChtObj .Left = 0 .Width = 600 .Height = 300 .Top = (i - 1) * 320 End With Next i End Sub
附近件kpi_3.rar为源excel可以下载解压来看到运行结果.