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

时间:2019-05-16 00:36:43

标签: java 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);
    }
}

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

2 个答案:

答案 0 :(得分:2)

好的,因为这是一个很好的问题,让我们举一个具体的示例,说明如何使用apache poi在Excel折线图中更改数据范围。

让我们从以下表格开始:

enter image description here

然后输入以下代码:

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();
 }
}

产生以下结果:

enter image description here

此代码使用org.openxmlformats.schemas.drawingml.x2006.chart.*类,并且可以与apache poi 3.17apache poi 4.1.0一起使用。

很遗憾,没有API公开的org.openxmlformats.schemas.drawingml.x2006.chart.*文档。因此,如果需要,我们需要从central.maven.org/maven2/org/apache/poi/ooxml-schemas/1.3下载ooxml-schemas-1.3-sources.jar。然后解压缩。然后转到目录ooxml-schemas-1.3,然后执行javadoc -d javadoc -sourcepath ./ -subpackages org。之后,我们在API中找到ooxml-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();

 }
}

答案 1 :(得分:0)

您可以通过将行高设置为零来从图表显示中删除数据,而不是添加新行。

首先,创建具有最大可能数据范围的图表,如下所示。 enter image description here

然后,使用以下代码设置您不想在图形中看到的高度为零的行。

    for(int i=8;i<14;i++) {
        sheet.getRow(i).setZeroHeight(true);;
    }

现在您将看到输出Excel更改为以下内容。

enter image description here

顺便说一句,您还可以通过将图形标题链接到单元格值来更新图形标题,就像上面的示例一样,图形标题链接到单元格A1。

enter image description here