如何使用POI在Word中添加图表?

时间:2019-08-29 17:18:23

标签: java apache-poi

我正在尝试在Word中添加图表。我们有一个带有示例图表的模板文件。我需要阅读并将其与新数据一起绘制,然后将其插入输出的Word文件中。

    XWPFDocument in_doc;
    try {
        in_doc = new XWPFDocument(new FileInputStream(TCellUtil.TCELL_DATA_LOG_FOLDER_PATH+File.separator+"chartTemp.docx"));

      XWPFChart chart = in_doc.getCharts().get(0);
      XSSFWorkbook chartDataWorkbook = chart.getWorkbook();
      String sheetName = chartDataWorkbook.getSheetName(0);
      XSSFSheet chartDataSheet = chartDataWorkbook.getSheet(sheetName);

      if (chart.getChartSeries().size() == 1) { // only one chart data
       XDDFChartData chartData = chart.getChartSeries().get(0);
       if (chartData.getSeries().size() == 1) { // exact two series

        int rMin = 1;
        int rMax = 3;

        // set new category data (both series)
        XDDFCategoryDataSource category = null;
        int c = 0;
        for (int r = rMin; r < rMax+1; r++) {
         chartDataSheet.getRow(r).getCell(c).setCellValue((String)data[r][c]); // in sheet
        }
        category = XDDFDataSourcesFactory.fromStringCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); // in chart

        // series 1
        XDDFChartData.Series series1 = chartData.getSeries().get(0);
        c = 1;
        // set new title
        String series1Title = (String)data[0][c];
        chartDataSheet.getRow(0).getCell(c).setCellValue(series1Title); // in sheet
        series1.setTitle(series1Title, new CellReference(sheetName, 0, c, true, true)); // in chart

        // set new values
        XDDFNumericalDataSource<Double> values = null;
        for (int r = rMin; r < rMax+1; r++) {
         chartDataSheet.getRow(r).getCell(c).setCellValue((Double)data[r][c]); // in sheet
        }
        values = XDDFDataSourcesFactory.fromNumericCellRange(chartDataSheet, new CellRangeAddress(rMin,rMax,c,c)); 
        series1.replaceData(category, values);
        series1.plot(); //in chart

       }
      }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

0 个答案:

没有答案