我只想有一个 FileOutputStream
将工作簿的内容写入应用程序中的文件,并在此 Excel 中创建多个工作表。我正在使用 Apache POI 读取/写入我的 Excel。我有以下方法来执行此操作 -
private static void writeToSpreadSheet(String test,Map<String,String> errorMap,Object object) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook()
HSSFSheet sheet = workbook.createSheet(test);
FileOutputStream fis = new FileOutputStream("output/test.xls");
//do stuff and finally write workbook contents to a file
workbook.write(fis);
if (fis != null)
fis.close();
}
我在这里面临的问题是,每次调用writeToSpreadSheet
时,都会创建一个新文件,并且现有数据会被覆盖。我只想要一个文件,并且
需要将新工作表添加到我现有的文件中。我如何实现这一目标?
最佳答案
我不在我的机器附近,所以我无法为您提供确切的代码库,但如果您按照确切的步骤操作,那么您可以获得所需的结果。
我已经从这里和那里组装了代码,它不会按原样工作。您必须修改代码并使其按照您想要的方式工作。我把这部分留给你。
final File file = "/output/test.xls";
HSSFWorkbook workbook = null;
FileOutputStream fileOut = new FileOutputStream(file);
private static void writeToSpreadSheet(String test,
Map<String, String> errorMap, Object object) throws IOException {
// Check whether your file exist
// if not then crate a workbook
// something like below
if (!file.exists()) {
System.out.println("Creating a new workbook '" + file + "'");
workbook = new HSSFWorkbook();
} else {
// create a method to get very last sheet number something like
// following .
int sheetIndex = getLastSheetIndex();
// if you dont to go with find last sheet index idea then you can
// create your unique name may be like timestamp or so
// add the new sheet with new index
HSSFSheet sheet = workbook.createSheet("Test Sheet " + sheetIndex);
// Write your content
workbook.write(fileOut);
fileOut.close();
}
}
private static int getLastSheetIndex() {
int sheetIndex = 1;
while (workbook.getSheet("Test Sheet " + sheetIndex) != null) {
sheetIndex++;
}
return sheetIndex;
}
目前你在做什么:
private static void writeToSpreadSheet(String test,
Map<String, String> errorMap, Object object) throws IOException {
// Creating the new workbook every time you call this method
HSSFWorkbook workbook = new HSSFWorkbook();
// Adding the same sheet to newly created workbook
HSSFSheet sheet = workbook.createSheet(test);
FileOutputStream fis = new FileOutputStream("output/test.xls");
// causing to overwrite your old workbook
workbook.write(fis);
if (fis != null)
fis.close();
}
关于java - 避免 Excel 中的文件内容被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25213633/