gpt4 book ai didi

java - 在 Java 中相对地将 excel 公式设置为整个列?

转载 作者:行者123 更新时间:2023-11-29 04:37:18 25 4
gpt4 key购买 nike

有什么办法可以在 Java 中将 excel 公式设置为整个列?

例如,在 excel 中,A 列和 B 列包含数字,C 列包含加法 A+B

我想对整个 C 列重复相同的公式,例如 C1 = A1+B1,C2=A2+B2。

目前,我正在通过一些肮脏的逻辑来执行此操作,该逻辑将 Number (1,2 ..so on ) 替换为行数。但在实际情况下,公式非常大且复杂,难以用上述策略替代。

Apache POI 是否提供任何类似 excel 的复制此类公式的功能?

最佳答案

Excel 的最佳实践方法是使用 R1C1 引用来解决这个问题。例如,使用此引用,我们可以将 =SUM(RC1:RC2) 应用于 C2:C10 范围。 R 表示这一行,C1 表示第 1 列 (A),C2 表示第 2 列 ( B).

不幸的是 apache poi 不支持 R1C1 引用。所以我能看到的唯一方法是为此使用 CellReferenceCellReference 可以获得 CellRefParts 作为单元格引用的三个部分、工作表名称(如果未提供则为 null)、基于 1 的行号和基于 A 的列字母。所以我们可以在公式中使用这些部分。

例子:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import java.io.*;

class UsingCellReferenceInFormula {

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

String[][] data = new String[][]{
{"Number1","Number2","Sum","Complex"},
{"123","456", null, null},
{"23.45","67.89", null, null},
{"123","-456", null, null},
{"-123.456","456.78", null, null}
};

Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();

int r = 0;
for(String[] dataRow : data){
Row row = sheet.createRow(r++);
int c = 0;
for(String dataCell : dataRow){
Cell cell = row.createCell(c++);
if ( r == 1 ) cell.setCellValue(dataCell);
else if ( c < 3 ) cell.setCellValue(Double.parseDouble(dataCell));
else if ( c == 3 ) {
CellReference cellReference = new CellReference(cell);
String thisR = cellReference.getCellRefParts()[1];
cell.setCellFormula("SUM(A" + thisR + ":B" + thisR + ")");
} else if ( c == 4 ) {
CellReference cellReference = new CellReference(cell);
String thisR = cellReference.getCellRefParts()[1];
cell.setCellFormula("IF(AND(A" + thisR + ">0,B" + thisR + ">0),SUM(A" + thisR + ":B" + thisR + "),MAX(A" + thisR + ":B" + thisR + "))");
}
}
}


FileOutputStream fileOut = new FileOutputStream("UsingCellReferenceInFormula.xlsx");
workbook.write(fileOut);
workbook.close();

}
}

关于java - 在 Java 中相对地将 excel 公式设置为整个列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com