import org.apache.poi.xddf.usermodel.chart.; import org.apache.poi.xwpf.usermodel.;

import java.io.FileOutputStream; import java.io.IOException;

public class WordChartExample {

public static void main(String[] args) {
    try {
        // 创建Word文档
        XWPFDocument document = new XWPFDocument();

        // 创建段落
        XWPFParagraph paragraph = document.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);

        // 创建运行
        XWPFRun run = paragraph.createRun();
        run.setText('数据折线图');
        run.setBold(true);
        run.setFontSize(16);

        // 创建图表
        XWPFChart chart = document.createChart(600, 400);

        // 创建数据系列
        XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
        XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
        leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

        // 创建数据源
        XDDFNumericalDataSource<Double> xs1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(11, 85, 0, 0));
        XDDFNumericalDataSource<Double> ys1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet1, new CellRangeAddress(11, 85, 2, 2));
        XDDFNumericalDataSource<Double> xs2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet2, new CellRangeAddress(11, 139, 0, 0));
        XDDFNumericalDataSource<Double> ys2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet2, new CellRangeAddress(11, 139, 2, 2));

        // 添加数据系列
        XDDFLineChartData data = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);
        XDDFLineChartData.Series series1 = (XDDFLineChartData.Series) data.addSeries(xs1, ys1);
        series1.setTitle('P9数据折线图', null);
        XDDFLineChartData.Series series2 = (XDDFLineChartData.Series) data.addSeries(xs2, ys2);
        series2.setTitle('P10数据折线图', null);

        // 绘制图表
        chart.plot(data);

        // 保存Word文档
        FileOutputStream fileOut = new FileOutputStream('温度.docx');
        document.write(fileOut);
        fileOut.close();

        System.out.println('折线图已导出到Word文档中。');

    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

Java POI 创建 Word 折线图 - 数据可视化

原文地址: https://www.cveoy.top/t/topic/f4hR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录