使用Apache Poi重命名XSSFTable的标头会导致损坏的XLSX文件

问题描述 投票:2回答:1

我正在尝试重命名现有xlsx文件的标头。我们的想法是使用excel文件将数据从XML导出到excel,并在某些用户进行调整后重新导入XML。

目前我们已经用Excel创建了一个“模板”xlsx-sheet,它已经包含一个可排序表(poi中的XSSFTable)和一个到XSD源的映射。然后我们通过POI导入它,将XML数据映射到它并保存。要将工作表调整为用户,我们要将此现有表的标题/列名称转换为不同的语言。它与POI 3.10-FINAL一起使用但是由于升级到4.0.1,它在打开时会导致损坏的xlsx文件。

我在stackoverflow上发现了这个问题已经Excel file gets corrupted when i change the value of any cell in the header (Columns Title)但它没有回答而且很老了。但我试图弄清楚评论的内容并试图压缩现有的XSSFTable,将填充的数据复制到新的工作表并为数据添加新的XSSFTable。可悲的是,这似乎相当复杂,所以我回到纠正破碎的标题单元格。我还尝试使用POI创建整个工作表并逐步使用“模板”-xslx,但我无法弄清楚如何实现我们的XSD-Mapping(在Excel中它的Developer-Tools - > Source - > Add然后映射动态表中某些单元的节点)

在poi升级之前工作的代码基本上是这样的:

//Sheet is the current XSSFSheet
//header is a Map with the original header-name from the template mapped to a the new translated name
//headerrownumber is the row containing the tableheader to be translated

 public static void translateHeaders(Sheet sheet,final Map<String,String> header,int headerrownumber) {
  CellRangeAddress address = new CellRangeAddress(headerrownumber,headerrownumber,0,sheet.getRow(headerrownumber).getLastCellNum());  //Cellrange is the header-row

        MyCellWalk cellWalk = new MyCellWalk (sheet,address);
        cellWalk.traverse(new CellHandler() {
            public void onCell(Cell cell, CellWalkContext ctx) {
                String val = cell.getStringCellValue();
                if (header.containsKey(val)) {
                    cell.setCellValue(header.get(val));
                }
            }
        });
}

MyCellWalk是一个org.apache.poi.ss.util.cellwalk.CellWalk,它遍历从左上角到右下角的单元格范围。

据我所知,它不足以简单地改变单元格的平坦值,因为xlsx在某些地图中保留了对单元名的引用,但我无法弄清楚如何抓取它们并重命名标题。也许翻译headernames还有另一种方法吗?

java excel apache-poi xssf
1个回答
1
投票

好吧,如果XSSFTable.updateHeaders不会失败,那么apache poi应该可以做到这一点。

以下所有内容均使用apache poi 4.0.1完成。

我已经下载了你的dummy_template.xlsx,然后尝试更改工作表中的表格列标题。但即使在调用XSSFTable.updateHeaders之后,XSSFTable中的列名也没有改变。所以我看了XSSFTable.java -> updateHeaders,以确定为什么这不会发生。我们发现:

if (row != null && row.getCTRow().validate()) {
 //do changing the column names
}

因此,如果根据XML名称空间,工作表中的相应行有效Office Open XML,则仅更改列名称。但在后来的Excel版本中(2007年之后)增加了额外的名称空间。在这种情况下,行的XML看起来像:

<row r="4" spans="1:3" x14ac:dyDescent="0.25">

请注意额外的x14ac:dyDescent属性。这就是row.getCTRow().validate()回归false的原因。

以下代码获取dummy_template.xlsx,重命名工作表中的列标题,然后调用撤防版本static void updateHeaders(XSSFTable table)。之后,result.xlsx有效在Excel开放。

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.util.cellwalk.*;

import org.apache.poi.xssf.usermodel.*;

import org.openxmlformats.schemas.spreadsheetml.x2006.main.*;

import java.io.*;
import java.util.*;

class ExcelRenameTableColumns {

 static void translateHeaders(Sheet sheet, final Map<String,String> header, int headerrownumber) {
  CellRangeAddress address = new CellRangeAddress(
   headerrownumber, headerrownumber, 
   0, sheet.getRow(headerrownumber).getLastCellNum());

  CellWalk cellWalk = new CellWalk (sheet, address);
  cellWalk.traverse(new CellHandler() {
   public void onCell(Cell cell, CellWalkContext ctx) {
    String val = cell.getStringCellValue();
    if (header.containsKey(val)) {
     cell.setCellValue(header.get(val));
    }
   }
  });
 }

 static void updateHeaders(XSSFTable table) {
  XSSFSheet sheet = (XSSFSheet)table.getParent();
  CellReference ref = table.getStartCellReference();

  if (ref == null) return;

  int headerRow = ref.getRow();
  int firstHeaderColumn = ref.getCol();
  XSSFRow row = sheet.getRow(headerRow);
  DataFormatter formatter = new DataFormatter();

System.out.println(row.getCTRow().validate()); // false!

  if (row != null /*&& row.getCTRow().validate()*/) {
   int cellnum = firstHeaderColumn;
   CTTableColumns ctTableColumns = table.getCTTable().getTableColumns();
   if(ctTableColumns != null) {
    for (CTTableColumn col : ctTableColumns.getTableColumnList()) {
     XSSFCell cell = row.getCell(cellnum);
     if (cell != null) {
      col.setName(formatter.formatCellValue(cell));
     }
     cellnum++;
    }
   }
  }
 }

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

  String templatePath = "dummy_template.xlsx";
  String outputPath = "result.xlsx";

  FileInputStream inputStream = new FileInputStream(templatePath);
  Workbook workbook = WorkbookFactory.create(inputStream);
  Sheet sheet = workbook.getSheetAt(0);

  Map<String, String> header = new HashMap<String, String>();
  header.put("textone", "Spalte eins");
  header.put("texttwo", "Spalte zwei");
  header.put("textthree", "Spalte drei");

  translateHeaders(sheet, header, 3);

  XSSFTable table = ((XSSFSheet)sheet).getTables().get(0);

  updateHeaders(table);

  FileOutputStream outputStream = new FileOutputStream(outputPath);
  workbook.write(outputStream);
  outputStream.close();
  workbook.close();

 }
}

如果我使用dummy_template.xlsx打开Excel 2007然后另存为dummy_template2007.xlsx,则行的XML将更改为

<row r="4" spans="1:3">

现在使用这个dummy_template2007.xlsx时,不需要手动调用XSSFTable.updateHeaders。由XSSFTable.writeTo调用的XSSFTable.commit会自动执行此操作。

© www.soinside.com 2019 - 2024. All rights reserved.