本文将介绍如何使用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);
}
}