我正在尝试使用JAVA Excel API vogella修改现有的Excel文件,但无法处理它。我找到了一种重新创建excel文件的方法,但这不是我想要的。有人可以给出建议,提示或分享一个简短的例子。
我正在分享我正在尝试做的事情:
/**
* Reading external file.
*
* @return Record[];
* @throws IOException;
* @throws BiffException.
*/
public Record[] read() throws IOException {
File inputWorkbook = new File(inputFile);
Workbook w;
Record[] records = null;
int rowsCount = 0;
try {
w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet(0);
int columnsCount = sheet.getColumns();
rowsCount = sheet.getRows();
records = new Record[rowsCount];
for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++) {
Record record = new Record(columnsCount);
for (int columnIndex = 0; columnIndex < columnsCount; columnIndex++) {
Cell cell = sheet.getCell(columnIndex, rowIndex);
String value = cell.getContents();
record.setRecordData(columnIndex, value);
}
records[rowIndex] = record;
}
} catch (BiffException e) {
errorMessage = 1;
}
return records;
}
/**
* Writing to existing excel file.
*
* @param records;
* @throws IOException;
* @throws WriteException;
* @throws BiffException.
*/
public void write(Record[] records) throws IOException, WriteException, BiffException {
File file = new File(inputFile);
WorkbookSettings wbSettings = new WorkbookSettings();
wbSettings.setLocale(new Locale("en", "EN"));
Workbook workbook = Workbook.getWorkbook(file, wbSettings);
WritableWorkbook writableworkbook = Workbook.createWorkbook(file, workbook, wbSettings);
WritableSheet excelSheet = writableworkbook.getSheet(0);
createLabel(excelSheet);
createContent(excelSheet, records);
writableworkbook.write();
writableworkbook.close();
}
答案 0 :(得分:1)
您提供的代码是专门写的,以覆盖已存在的代码。此行:
for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++)
总是从第0行开始,因此会覆盖那里的所有内容。
此外,您之前正在致电:
rowsCount = sheet.getRows();
这将告诉您已填充了多少行。如果您在最后一个填充的行之后开始填充,那么您将保留已存在的所有内容。