本文将介绍如何使用spire.xls for java在excel文档中使用不连续的数据创建图表。
原excel文档如下:
import com.spire.xls.*;
import com.spire.xls.charts.chartserie;
import java.awt.*;
public class chartwithnoncontiguousdata {
public static void main(string[] args){
//创建workbook实例
workbook workbook = new workbook();
//加载excel文档
workbook.loadfromfile("noncontiguousdata.xlsx");
//获取第一个工作表
worksheet sheet = workbook.getworksheets().get(0);
//添加柱状图表
chart chart = sheet.getcharts().add(excelcharttype.columnclustered);
chart.setseriesdatafromrange(false);
//指定图表的位置
chart.setleftcolumn(1);
chart.settoprow(10);
chart.setrightcolumn(10);
chart.setbottomrow(24);
//添加两个系列到图表,调用xlsrange.addcombinedrange(cellrange cr)方法为系列设置多个不连贯的数据区域
chartserie cs1 = (chartserie)chart.getseries().add();
cs1.setname(sheet.getcellrange("b1").getvalue());
cs1.setcategorylabels(sheet.getcellrange("a2:a3").addcombinedrange(sheet.getcellrange("a5:a6")).addcombinedrange(sheet.getcellrange("a8:a9")));
cs1.setvalues(sheet.getcellrange("b2:b3").addcombinedrange(sheet.getcellrange("b5:b6")).addcombinedrange(sheet.getcellrange("b8:b9")));
cs1.setserietype(excelcharttype.columnclustered);
chartserie cs2 = (chartserie)chart.getseries().add();
cs2.setname(sheet.getcellrange("c1").getvalue());
cs2.setcategorylabels(sheet.getcellrange("a2:a3").addcombinedrange(sheet.getcellrange("a5:a6")).addcombinedrange(sheet.getcellrange("a8:a9")));
cs2.setvalues(sheet.getcellrange("c2:c3").addcombinedrange(sheet.getcellrange("c5:c6")).addcombinedrange(sheet.getcellrange("c8:c9")));
cs2.setserietype(excelcharttype.columnclustered);
//设置图表标题
chart.setcharttitle("图表");
chart.getcharttitlearea().getfont().setsize(15);
chart.getcharttitlearea().setcolor(color.black);
chart.getprimaryvalueaxis().hasmajorgridlines(false);
//保存结果文档
workbook.savetofile("chart.xlsx", excelversion.version2013);
}
}