[英]Apache poi populate the cell value by formula
我是 apache poi 的新手,试图编写 excel 文件我在将公式设置为单元格时遇到了一些问题。
下面是我的示例 excel:
用户 | 国家 | 价值 |
---|---|---|
罗希特 | 英国 | |
约翰 | IND |
我需要根据User和Country字段填充Value列。 下面是 excel 公式,我想将其转换为 apache poi java
=IF(AND(LEN([@[User]]) > 0, [@Country] = "UK"),1,0)
有谁能够帮我?
示例代码
try {
InputStream inputStream = this.getClass().getResourceAsStream("/sample.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook (inputStream);
System.out.println("inside the controller");
XSSFSheet sheet = workbook.getSheetAt(0);
Object[][] bookData = {
{"Rohit","UK",null},
{"John","IND",null}
};
int rowCount = sheet.getLastRowNum();
int count=0;
//CellStyle cell1;
for (Object[] aBook : bookData) {
Row row = sheet.createRow(++rowCount);
int columnCount = 0;
Cell cell = row.createCell(columnCount);
// cell.setCellValue(rowCount);
for (Object field : aBook) {
cell = row.createCell(columnCount++);
if(field==null){
cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=UK),1,0)");
}
else if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
}
}
}
java.util.List<XSSFTable> l = sheet.getTables();
l.get(0).getCTTable().setRef("A1:L4");
FileOutputStream outputStream = new FileOutputStream("D://demo/sample_with_values.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException | EncryptedDocumentException ex) {
ex.printStackTrace();
}
正如@Axel Richter
提到的那样,使用==
是无效的。
cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)==UK),1,0)");
你的公式有误。
#1。 错误...
Parse error near char 25 '=' in specified formula 'IF(AND(LEN(A1:A3)>0,(B1:B3)==UK),1,0)'. Expected cell ref or constant literal`
…表示您在公式中使用了额外的=
。
#2。 (B1:B3)==UK
应该是(B1:B3)="UK"
。 您正在比较一个字符串值,所以它应该用双引号引起来。
代码:
cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=\"UK\"),1,0)");
Output :
public static void main(String[] args) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet spreadsheet = workbook.createSheet("example");
HSSFRow row = spreadsheet.createRow((short) 0);
row.createCell(0).setCellValue("User");
row.createCell(1).setCellValue("Country");
row.createCell(2).setCellValue("Value");
row = spreadsheet.createRow((short) 1);
row.createCell(0).setCellValue("Rohit");
row.createCell(1).setCellValue("UK");
row.createCell(2).setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=\"UK\"),1,0)");
row = spreadsheet.createRow((short) 2);
row.createCell(0).setCellValue("John");
row.createCell(1).setCellValue("IND");
row.createCell(2).setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=\"UK\"),1,0)");
FileOutputStream out =
new FileOutputStream(
new File("/Users/anand.keshri/workspace/poi/first.xls")
);
workbook.write(out);
out.close();
workbook.close();
System.out.println("first.xls written successfully");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.