Hi All,
I want to add new sheets to existing excel file, but when file doesn't exist it it successfully
created and even opens successfully with the data and when i try to add new sheet to this
existing file it doesn't throw any error but when i try to open this file it throws error
saying "We found a problem with some content in 'filename' ? Do you want us to try to recover..........".
Code is pasted below. Please look into it and help me out.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class FileCheck {
public static void main(String[] args) {
XSSFWorkbook workbook = new XSSFWorkbook();
String fileName="Trial.xlsx";
File file = new File(fileName);
FileOutputStream out;
if(!file.exists()){ // This will create new workbook with new sheet if it doesnt exists{
System.out.println("New");
XSSFSheet mySheet = workbook.createSheet("A");
} else{ // This add new sheet to above created workbook
try {
System.out.println("Old");
XSSFWorkbook myWorkBook = (XSSFWorkbook) WorkbookFactory.create(file);
workbook=myWorkBook;
XSSFSheet mySheet = (XSSFSheet) workbook.createSheet("B");
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try{
out = new FileOutputStream(fileName,true);
workbook.write(out);
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
Thanks,
Aakash Rathod
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@poi.apache.org
For additional commands, e-mail: dev-help@poi.apache.org
|