Bootstrap

java生成word中含有折现图

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

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

public class WordWithLineChart {
    public static void main(String[] args) throws IOException {
        // 创建文档对象
        XWPFDocument document = new XWPFDocument();

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

        // 创建图表
        XWPFChart chart = createLineChart(document);

        // 将图表添加到段落中
        XWPFRun run = paragraph.createRun();
        String blipId = document.addPictureData(chart.getGraphicalChartData().getInputStream(), Document.PICTURE_TYPE_PNG);
        int width = Units.toEMU(500);
        int height = Units.toEMU(300);
        run.addPicture(blipId, Document.PICTURE_TYPE_PNG, "Line Chart", width, height);

        // 保存文档
        FileOutputStream out = new FileOutputStream("chart.docx");
        document.write(out);
        out.close();

        System.out.println("Word document with line chart created successfully.");
    }

    private static XWPFChart createLineChart(XWPFDocument doc) {
        XWPFChart chart = doc.createChart(10, 10, 500, 300);  // 创建图表对象

        // 创建数据源
        XDDFDataSource<String> categoryDataSource = XDDFDataSourcesFactory.fromStringCellRange(doc.getTableArray(0), new CellRangeAddress(1, 4, 0, 0));
        XDDFNumericalDataSource<Double> valueDataSource = XDDFDataSourcesFactory.fromNumericCellRange(doc.getTableArray(0), new CellRangeAddress(1, 4, 1, 1));

        // 创建坐标轴
        XDDFCategoryAxis categoryAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
        XDDFValueAxis valueAxis = chart.createValueAxis(AxisPosition.LEFT);
        valueAxis.setCrosses(AxisCrosses.AUTO_ZERO);

        // 创建图表数据
        XDDFChartData data = chart.createData(ChartTypes.LINE, categoryAxis, valueAxis);
        XDDFLineChartData lineData = (XDDFLineChartData) data;
        XDDFLineChartData.Series series = (XDDFLineChartData.Series) lineData.addSeries(categoryDataSource, valueDataSource);
        series.setTitle("Sample Data", null);

        // 配置图表样式
        chart.plot(data);

        return chart;
    }
}
;