我希望只有一个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
时,都会创建一个新文件,现有数据将被覆盖。我想要一个文件 ,和
需要将新工件添加到我现有的文件中。我如何实现这一目标?
答案 0 :(得分:1)
我不在我的机器附近,因此我无法为您提供确切的代码库,但如果您按照确切的步骤操作,那么您可以获得所需的结果。
我已经从这里和那里汇集了代码,它不会按原样运行。您必须修改代码并使其按您希望的方式工作。我把那部分留给你了。
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();
}