What I want to do is ask the user if they want to create a new or select an existing Excel workbook. Selecting an existing file is no problem. However I get an error saying "Your file appears not to be a valid OLE2 document" as soon as I create a name for a new Excel file.
public void selectExcelFile() {
String excelFileName = null; // the name/directory/address of the excel file created/selected
FileInputStream excelFileIn = null; // allows us to connect to the Excel file so we can read it
FileOutputStream excelFileOut = null; // allows us to connect to the Excel file so we can write to it
ExcelFileUtility eUtil = new ExcelFileUtility(); // used open an excel file
if(columnsQuery != null) {
try {
excelFileName = eUtil.getFile(FileExtensions.XLS); // file extension = ".xls"
if(excelFileName != null) {
excelFileIn = new FileInputStream(new File(excelFileName));
workbook = new HSSFWorkbook(excelFileIn);
exportColsToWorkbook(columnsQuery);
excelFileOut = new FileOutputStream(excelFileName);
workbook.write(excelFileOut);
// close everything
workbook.close();
excelFileIn.close();
excelFileOut.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
And then:
public String getFile(String extension) {
String result = null;
if(extension != null) {
int choice = askIfNewFile();
if(choice == 0) { // yes, create new file
result = createFile(extension);
}
else { // no, select existing file
result = getFileLocation();
}
}
else {
System.out.println("No file extension.");
}
return result;
}
public String createFile(String extension) throws IOException {
String newFileName = "";
File newFile = null;
boolean isCreated = false;
JFrame frame = new JFrame("Creating a New ." + extension + " File");
String result = null;
String dir = getFileDirectory();
System.out.println("DIR: " + dir);
if(dir != null) {
while(newFileName.isEmpty() || newFileName == null) {
// Used WorkbookUtil.createSafeSheetName to validate file name
// Please replace if there is a better option
newFileName = WorkbookUtil.createSafeSheetName(JOptionPane.showInputDialog(frame, "Enter new ." + extension + " file name:"));
}
newFile = new File(dir + "\\" + newFileName + "." + extension);
System.out.