Ari*_*iel 3 java apache-poi apache-poi-4
我试图copyRowFrom(...);将电子表格的第一行复制到新 XSSFSheet 的第一行,但有些东西无法正常工作。您可以在此处找到 XSSFRow 类和方法:
https://github.com/apache/poi/blob/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFRow.java#L581
我IllegalArgumentException("amountToMove must not be zero")从 FormulaShifter.java 获取:
https://github.com/apache/poi/blob/trunk/src/java/org/apache/poi/ss/formula/FormulaShifter.java#L80
问题似乎出在 XSSFRow 的第 623 行,其中FormulaShifter.createForRowCopy(...)使用参数调用rowDifference = 0,因为源行为 0,目标行为 0:
https: //github.com/apache/poi/blob/trunk/src/ooxml/java/org /apache/poi/xssf/usermodel/XSSFRow.java#L623
我不知道,也许这是一个错误,但是当到达 FormulaShifter.java 中的第 80 行时,参数 rowDifference 对应的 amountToMove 为 0,因此它抛出 IllegalArgumentException。
copyRowFrom(...);我是否遗漏了某些内容,或者这是XSSFRow 中方法的错误?
你是对的。这是一个错误,XSSFRow因为即使没有任何内容需要移动,它也会调用FormulaShifter.createForRowCopy,因为目标行号与源行号相同。您可以将此作为错误提交到apache poi.
但随后需要创建一个可以在那里提供的测试用例。我已经为你做到了。该代码还提供了一种解决方法。这是首先复制到错误的目标行,其中行号与源行号不同。然后它将错误的第一个目标行复制到真正需要的目标行。
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
class ExcelCopyRowFrom {
public static void main(String[] args) throws Exception {
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));
XSSFSheet srcSheet = workbook.getSheetAt(0);
XSSFRow srcRow = srcSheet.getRow(0);
XSSFSheet destSheet = workbook.createSheet();
//XSSFRow destRow = destSheet.createRow(0); //this fails because destination row number is the same as source row number
XSSFRow destRow = destSheet.createRow(1); //this works
destRow.copyRowFrom(srcRow, new CellCopyPolicy());
//workaround copy wrong first destination row to really needed destination row
XSSFRow destRowNeeded = destSheet.createRow(0);
destRowNeeded.copyRowFrom(destRow, new CellCopyPolicy());
//the remove wrong first destination row
destSheet.removeRow(destRow);
FileOutputStream outputStream = new FileOutputStream("SAMPLENEW.xlsx");
workbook.write(outputStream);
outputStream.close();
workbook.close();
}
}
Run Code Online (Sandbox Code Playgroud)