Java POI Excel 折线图创建 - 使用 A2:A66 列作为横轴数据源
import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xddf.usermodel.chart.; import org.apache.poi.xssf.usermodel.;
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException;
public class ExcelChartExample04 {
public static void main(String[] args) {
try {
// 读取Excel文件
FileInputStream fileIn = new FileInputStream('input.xlsx');
XSSFWorkbook workbook = new XSSFWorkbook(fileIn);
XSSFSheet sheet1 = workbook.getSheet('P1');
// 创建折线图
XSSFDrawing drawing = sheet1.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 3, 9, 9, 19);
XSSFChart chart = drawing.createChart(anchor);
chart.setTitleText('数据折线图');
chart.setTitleOverlay(false);
// 设置图例位置
XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.BOTTOM);
// 设置横坐标轴
XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
bottomAxis.setMajorTickMark(AxisTickMark.CROSS);
bottomAxis.setMinorTickMark(AxisTickMark.NONE);
bottomAxis.setCrosses(AxisCrosses.AUTO_ZERO);
bottomAxis.setTitle('时间');
bottomAxis.setTickLabelPosition(AxisTickLabelPosition.NEXT_TO);
// 设置纵坐标轴
XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
leftAxis.setTitle('数据值');
// 设置数据源
XDDFNumericalDataSource<Double> xs1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 0, 0)); // A2:A66
XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 1, 1)); // B2:B66
XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(1, 66, 2, 2)); // C2:C66
// 添加数据系列
XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs1, ys1);
series1.setTitle('P1数据折线图', null);
XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs1, ys2);
series2.setTitle('P1数据折线图', null);
// 绘制图表
chart.plot(data);
// 保存Excel文件
FileOutputStream fileOut = new FileOutputStream('input.xlsx');
workbook.write(fileOut);
fileOut.close();
System.out.println('折线图已创建并保存到Excel文件中。');
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文地址: https://www.cveoy.top/t/topic/fSH2 著作权归作者所有。请勿转载和采集!