使用 Apache POI 更改 Excel 折线图中的数据范围

Pyr*_*yro 6 java charts apache-poi xssf

我想看看是否可以使用 Apache POI 更改折线图中系列的数据范围。

我能够从图表本身中提取系列,但找不到允许我更改数据范围的方法。

XSSFWorkbook workbook = new XSSFWorkbook("C:\\Workbook.xlsx");
Sheet worksheet = workbook.getSheetAt(0);
XSSFDrawing drawing = (XSSFDrawing) worksheet.createDrawingPatriarch();
List<XSSFChart> charts = drawing.getCharts();
for (XSSFChart chart : charts) {
    String title = chart.getTitleText().toString();
    if (title.equals("Z-Acceleration")) {
        CTChart cc = chart.getCTChart();
        CTPlotArea plotArea = cc.getPlotArea();
        CTLineSer[] ccc = plotArea.getLineChartArray()[0].getSerArray();
        for (CTLineSer s : ccc) {
            System.out.println(s.xmlText());
        }
        System.out.println(ccc.length);
    }
}
Run Code Online (Sandbox Code Playgroud)

我打印出 XML 文本以查看它是否确实能够正确地从图表中提取系列并能够找到其标题和数据范围,但无法更改它。

Axe*_*ter 6

好的,既然这是一个很好的问题,让我们举一个具体的例子来说明如何使用apache poi.

让我们从以下工作表开始:

在此处输入图片说明

然后如下代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.SpreadsheetVersion;

import org.openxmlformats.schemas.drawingml.x2006.chart.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.List;

class ExcelChangeChartDataSource {

 static XSSFChart getChartWithTitle(XSSFSheet sheet, String wantedTitle) {
  if (sheet == null || wantedTitle == null) return null;
  XSSFDrawing drawing = sheet.createDrawingPatriarch();
  List<XSSFChart> charts = drawing.getCharts();
  for (XSSFChart chart : charts) {
   String title = chart.getTitleText().toString();
   if (wantedTitle.equals(title)) return chart;
  }
  return null;
 }

 static void addMonthDataToChart(XSSFSheet sheet, XSSFChart chart, String month, Double[] seriesData) {
  CTChart ctChart = chart.getCTChart();
  CTPlotArea ctPlotArea = ctChart.getPlotArea();
  List<CTLineSer> ctLineSerList = ctPlotArea.getLineChartArray(0).getSerList();

  Row row;
  Cell cell;
  int ser = 0;
  for (CTLineSer ctLineSer : ctLineSerList) {

   CTAxDataSource cttAxDataSource = ctLineSer.getCat();
   CTStrRef ctStrRef = cttAxDataSource.getStrRef();

   AreaReference catReference = new AreaReference(ctStrRef.getF(), SpreadsheetVersion.EXCEL2007);
   CellReference firstCatCell = catReference.getFirstCell();
   CellReference lastCatCell = catReference.getLastCell();
   if (firstCatCell.getCol() == lastCatCell.getCol()) {
    int col = firstCatCell.getCol();
    int lastRow = lastCatCell.getRow();
    row = sheet.getRow(lastRow+1); if (row == null) row = sheet.createRow(lastRow+1);
    cell = row.getCell(col); if (cell == null) cell = row.createCell(col);
    cell.setCellValue(month);

    ctStrRef.setF(new AreaReference(
                  firstCatCell, 
                  new CellReference(lastCatCell.getSheetName(), lastRow+1, col, true, true), 
                  SpreadsheetVersion.EXCEL2007).formatAsString()
                 );

    CTNumDataSource ctNumDataSource = ctLineSer.getVal();
    CTNumRef ctNumRef = ctNumDataSource.getNumRef();

    AreaReference numReference = new AreaReference(ctNumRef.getF(), SpreadsheetVersion.EXCEL2007);
    CellReference firstNumCell = numReference.getFirstCell();
    CellReference lastNumCell = numReference.getLastCell();
    if (lastNumCell.getRow() == lastRow && firstNumCell.getCol() == lastNumCell.getCol()) {
     col = firstNumCell.getCol();
     row = sheet.getRow(lastRow+1); if (row == null) row = sheet.createRow(lastRow+1);
     cell = row.getCell(col); if (cell == null) cell = row.createCell(col);
     if (ser < seriesData.length) cell.setCellValue(seriesData[ser]);

     ctNumRef.setF(new AreaReference(
                   firstNumCell, 
                   new CellReference(lastNumCell.getSheetName(), lastRow+1, col, true, true), 
                   SpreadsheetVersion.EXCEL2007).formatAsString()
                  );
    }
   }
   ser++;
  }
 }

 public static void main(String[] args) throws Exception {

  XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("WorkbookWithChart.xlsx"));

  XSSFSheet sheet = workbook.getSheetAt(0);

  XSSFChart chart = getChartWithTitle(sheet, "Z-Acceleration"); 

  if (chart != null) {
   addMonthDataToChart(sheet, chart, "Apr", new Double[]{7d,3d,5d});
   addMonthDataToChart(sheet, chart, "Mai", new Double[]{2d,6d,8d});
   addMonthDataToChart(sheet, chart, "Jun", new Double[]{1d,9d,4d});
   addMonthDataToChart(sheet, chart, "Jul", new Double[]{5d,6d});
  }

  FileOutputStream out = new FileOutputStream("WorkbookWithChartNew.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();
 }
}
Run Code Online (Sandbox Code Playgroud)

产生以下结果:

在此处输入图片说明

此代码使用org.openxmlformats.schemas.drawingml.x2006.chart.*类,可以apache poi 3.17apache poi 4.1.0.

不幸的是,没有任何可用APIorg.openxmlformats.schemas.drawingml.x2006.chart.*公共文档。所以如果我们需要它,我们需要ooxml-schemas-1.3-sources.jarcentral.maven.org/maven2/org/apache/poi/ooxml-schemas/1.3下载。然后解压那个。然后转到目录ooxml-schemas-1.3并执行javadoc -d javadoc -sourcepath ./ -subpackages org. 之后,我们APIooxml-schemas-1.3/javadoc. 开始阅读overview-tree.html

因为apache poi 4.1.0我们需要ooxml-schemas-1.4.

我也尝试过使用新XDDF东西apache poi 4.1.0。但起初代码并不是真的便宜得多,其次这有一个缺点,XDDFChart.plot当一些数据XDDFNumericalDataSource<Double> values不存在时会失败。然后我们必须将这些数据点设置为 0。但这与不存在不同。所以XDDF在这种情况下使用新东西并不是真正的进步。但尽管如此,这是代码,我已经尝试过:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.SpreadsheetVersion;

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

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.util.List;

class ExcelChangeChartDataSource {

 static XSSFChart getChartWithTitle(XSSFSheet sheet, String wantedTitle) {
  if (sheet == null || wantedTitle == null) return null;
  XSSFDrawing drawing = sheet.createDrawingPatriarch();
  List<XSSFChart> charts = drawing.getCharts();
  for (XSSFChart chart : charts) {
   String title = chart.getTitleText().toString();
   if (wantedTitle.equals(title)) return chart;
  }
  return null;
 }

 static void addMonthDataToChart(XSSFSheet sheet, XSSFChart chart, String month, Double[] seriesData) {
  Row row;
  Cell cell;

  List<XDDFChartData> chartDataList = chart.getChartSeries();
  XDDFChartData chartData = chartDataList.get(0);

  List<XDDFChartData.Series> seriesList = chartData.getSeries();
  int ser = 0;
  for (XDDFChartData.Series series : seriesList) {
   XDDFDataSource categoryData = series.getCategoryData();
   AreaReference catReference = new AreaReference(categoryData.getDataRangeReference(), SpreadsheetVersion.EXCEL2007);
   CellReference firstCatCell = catReference.getFirstCell();
   CellReference lastCatCell = catReference.getLastCell();
   if (firstCatCell.getCol() == lastCatCell.getCol()) {
    int col = firstCatCell.getCol();
    int lastRow = lastCatCell.getRow();
    row = sheet.getRow(lastRow+1); if (row == null) row = sheet.createRow(lastRow+1);
    cell = row.getCell(col); if (cell == null) cell = row.createCell(col);
    cell.setCellValue(month);

    XDDFDataSource<String> category = XDDFDataSourcesFactory.fromStringCellRange(
                                       sheet, 
                                       new CellRangeAddress(firstCatCell.getRow(), lastRow+1, col, col));

    XDDFNumericalDataSource valuesData = series.getValuesData();
    AreaReference numReference = new AreaReference(valuesData.getDataRangeReference(), SpreadsheetVersion.EXCEL2007);
    CellReference firstNumCell = numReference.getFirstCell();
    CellReference lastNumCell = numReference.getLastCell();
    if (lastNumCell.getRow() == lastRow && firstNumCell.getCol() == lastNumCell.getCol()) {
     col = firstNumCell.getCol();
     row = sheet.getRow(lastRow+1); if (row == null) row = sheet.createRow(lastRow+1);
     cell = row.getCell(col); if (cell == null) cell = row.createCell(col);
     if (ser < seriesData.length) cell.setCellValue(seriesData[ser]);
     else cell.setCellValue(0); // Here we need set 0 where it not should be needed.

     XDDFNumericalDataSource<Double> values = XDDFDataSourcesFactory.fromNumericCellRange(
                                               sheet, 
                                               new CellRangeAddress(firstNumCell.getRow(), lastRow+1, col, col));

     series.replaceData(category, values);
    }
   }
   ser++;
  }
  chart.plot(chartData);
 }

 public static void main(String[] args) throws Exception {

  XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("WorkbookWithChart.xlsx"));

  XSSFSheet sheet = workbook.getSheetAt(0);

  XSSFChart chart = getChartWithTitle(sheet, "Z-Acceleration"); 

  if (chart != null) {
   addMonthDataToChart(sheet, chart, "Apr", new Double[]{7d,3d,5d});
   addMonthDataToChart(sheet, chart, "Mai", new Double[]{2d,6d,8d});
   addMonthDataToChart(sheet, chart, "Jun", new Double[]{1d,9d,4d});
   addMonthDataToChart(sheet, chart, "Jul", new Double[]{5d,6d});
  }

  FileOutputStream out = new FileOutputStream("WorkbookWithChartNew.xlsx");
  workbook.write(out);
  out.close();
  workbook.close();

 }
}
Run Code Online (Sandbox Code Playgroud)