我想在现有工作簿中插入值。这里封装了这个逻辑的类:
public class FormulaExtractor {
private String pathToExcelFile;
private XSSFWorkbook workbook;
private Map<Double, Formula> idFormular = new HashMap<>();
public FormulaExtractor(String pathToExcelFile) {
this.pathToExcelFile = pathToExcelFile;
try (FileInputStream fileInputStream = new FileInputStream(new File(pathToExcelFile))) {
this.workbook = new XSSFWorkbook(fileInputStream);
} catch (FileNotFoundException e) {
System.out.println("Cannot locate a xls file. Exception: " + e.toString());
} catch (IOException e) {
System.out.println("IO exception " + e.toString());
}
}
public void insertHumanReadableFormulas() throws IOException {
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
Cell cell = currentRow.createCell(CellReference.convertColStringToIndex("K"));
cell.setCellValue("Some dummy variable to test. ");
}
FileOutputStream fileOut = new FileOutputStream(new File(this.pathToExcelFile));
workbook.write(fileOut);
fileOut.close();
}
}
我如何使用它:
public class App {
public static void main(String[] args) throws IOException {
final String pathToExcel = "some/path/some_excel.xlsx";
FormulaExtractor formulaExtractor = new FormulaExtractor(pathToExcel);
formulaExtractor.insertHumanReadableFormulas();
}
}
我没有任何异常或错误。当我打开我的Excel文件时,我根本找不到列“K”中的值。我做错了什么?