POI 5.2.2版本中添加次要坐标轴的代码示例
在POI 5.2.2版本中,没有直接提供添加次要坐标轴的方法。次要坐标轴是一种在图表中显示多个不同范围的坐标轴的方式,可以用来展示不同单位或不同数据类型的数据。
要实现次要坐标轴,可以使用POI的底层库Apache poi-ooxml-schemas来创建自定义的图表XML,并将其插入到Excel文件中。以下是一个添加次要坐标轴的示例代码:
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.charts.*;
import org.openxmlformats.schemas.drawingml.x2006.chart.*;
import java.io.FileOutputStream;
public class SecondaryAxisExample {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
XSSFSheet sheet = workbook.createSheet("Chart");
// Create a sample dataset
XSSFRow row;
XSSFCell cell;
for (int i = 0; i < 10; i++) {
row = sheet.createRow(i);
cell = row.createCell(0);
cell.setCellValue(i);
cell = row.createCell(1);
cell.setCellValue(i * 10);
}
// Create a chart
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 4, 2, 12, 15);
XSSFChart chart = drawing.createChart(anchor);
// Create chart axis
XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
XDDFValueAxis rightAxis = chart.createValueAxis(AxisPosition.RIGHT);
// Set the axis cross between
leftAxis.crossAxis(rightAxis);
rightAxis.crossAxis(leftAxis);
// Set the axis position
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
rightAxis.setCrosses(AxisCrosses.MAX);
// Create chart data sources
XDDFDataSource<Double> leftAxisDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 9, 0, 0));
XDDFDataSource<Double> rightAxisDataSource = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, 9, 1, 1));
// Create left axis plot
XDDFLineChartData leftAxisData = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
XDDFLineChartData.Series leftAxisSeries = (XDDFLineChartData.Series) leftAxisData.addSeries(leftAxisDataSource, null);
leftAxisSeries.setTitle('Left Axis', null);
// Create right axis plot
XDDFLineChartData rightAxisData = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, rightAxis);
XDDFLineChartData.Series rightAxisSeries = (XDDFLineChartData.Series) rightAxisData.addSeries(rightAxisDataSource, null);
rightAxisSeries.setTitle('Right Axis', null);
// Combine left and right axis plots
leftAxisData.combine(rightAxisData);
// Plot the chart
chart.plot(leftAxisData);
// Save the workbook
try (FileOutputStream fileOut = new FileOutputStream("chart_with_secondary_axis.xlsx")) {
workbook.write(fileOut);
}
}
}
}
这个示例代码创建了一个包含两列数据的Excel表格,并在图表中展示了这两列数据。左侧的坐标轴显示第一列数据,右侧的坐标轴显示第二列数据。
原文地址: https://www.cveoy.top/t/topic/lajI 著作权归作者所有。请勿转载和采集!