【发布时间】:2018-05-12 03:46:18
【问题描述】:
我有一个 Java 代码,我在其中创建了一个新的 .xlsm 文件,我创建该文件以镜像另一个空的 .xlsm 文件的格式。我的问题是当我在这个新创建的 .xlsm 的特定单元格中设置公式时。当我打开文件时,单元格显示:#NAME?。但是当我在单元格中按回车键时,公式会正确显示。当我出去的时候,这个公式就起作用了。
为什么会这样?
Java代码如下:
public static String main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/database" ,
"user" ,
"password"
);
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from `table`");
FileInputStream file = new FileInputStream(new File("C:\\Users\\Desktop\\Folder1.xlsm"));
XSSFWorkbook wb = new XSSFWorkbook(OPCPackage.open(file));
XSSFSheet spreadsheet = wb.getSheet("Planilha1");
XSSFRow row = spreadsheet.createRow(1);
XSSFCell cell;
int i = 1;
while(resultSet.next()) {
row = spreadsheet.createRow(i);
cell = row.createCell(1);
cell.setCellValue("");
cell = row.createCell(2);
cell.setCellValue(resultSet.getString("column1"));
i++;
}
XSSFRow linhacontador = spreadsheet.getRow(1);
if (linhacontador == null) {
linhacontador = spreadsheet.createRow(1);
}
XSSFCell colunacontador = linhacontador.getCell(34);
if (colunacontador == null) {
colunacontador = linhacontador.createCell(34);
}
colunacontador.setCellType(XSSFCell.CELL_TYPE_FORMULA);
colunacontador.setCellFormula("CONT.SE(AH:AH, \"<>\")");
CellRangeAddress range = new CellRangeAddress(1, i-1, 25, 25);
spreadsheet.addMergedRegion(range);
FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Desktop\\exceldatabase.xlsm"));
wb.write(out);
out.close();
connect.close();
return "Worksheet Done!";
}
显然我的问题在这里:
colunacontador.setCellType(XSSFCell.CELL_TYPE_FORMULA);
colunacontador.setCellFormula("CONT.SE(AH:AH, \"<>\")");
【问题讨论】:
-
你能试试这个公式的“英文版”吗..(COUNTIF)? stackoverflow.com/a/15254518/592355, stackoverflow.com/questions/17224631/…
-
好的,我会试试的。让我等一下
-
其实可以的!我写了 COUNT.IF 并且不工作,当我删除点时,工作。谢谢@xerx593
标签: java excel excel-formula apache-poi