2015-11-23 67 views
0

我想要做的是詢問用戶他們是否想創建一個新的或選擇一個現有的Excel工作簿。選擇一個現有的文件是沒有問題的。但是,只要爲新的Excel文件創建名稱,就會收到錯誤消息,說明「您的文件似乎不是有效的OLE2文檔」。NotOLE2FileException:無效的標頭簽名;讀取0x0000000000000000,預期0xE11AB1A1E011CFD0

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(); 
     } 

    } 
} 

然後:

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.println(newFile.toString()); 

     try { 
      isCreated = newFile.createNewFile(); 

      if(isCreated) { 
       result = newFile.getAbsolutePath(); 
      } 
      else { 
       System.out.println("File already exists."); 
      } 
     } 
     catch(IOException ioe) { 
      System.out.println(ioe); 
     } 
    } 
    return result; 
} 

public String getFileLocation() { 
    String result = null; 
    JFileChooser pickFile = new JFileChooser(); 

    if (pickFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
     try { 
      result = pickFile.getSelectedFile().getCanonicalPath(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     // check if file exists 
    } 
    System.out.println("File location: " + result); 

    return result; 
} 

public String getFileDirectory() { 
    String result = null; 

    JFileChooser pickFile = new JFileChooser(); 

    pickFile.setDialogTitle("Choose Folder"); 
    pickFile.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
    pickFile.setAcceptAllFileFilterUsed(false); 

    if (pickFile.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
     result = pickFile.getSelectedFile().toString(); 
    } 
    else { 
     System.out.println("No Selection "); 
    } 

    return result; 
} 

以下是錯誤我得到:

org.apache.poi.poifs.filesystem.NotOLE2FileException: Invalid header signature; read 0x0000000000000000, expected 0xE11AB1A1E011CFD0 - Your file appears not to be a valid OLE2 document 
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:162) 
at org.apache.poi.poifs.storage.HeaderBlock.<init>(HeaderBlock.java:112) 
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:300) 
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:400) 
at org.apache.poi.hssf.usermodel.HSSFWorkbook.<init>(HSSFWorkbook.java:381) 
at mhhls.him.dbtoexcel.program.DBtoExcel.selectExcelFile(DBtoExcel.java:159) 
at mhhls.him.dbtoexcel.program.DBtoExcel.exportToExcel(DBtoExcel.java:422) 
at mhhls.him.dbtoexcel.ui.main.DBtoExcelWindow$7.actionPerformed(DBtoExcelWindow.java:183) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.setPressed(Unknown Source) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
at java.awt.Component.processMouseEvent(Unknown Source) 
at javax.swing.JComponent.processMouseEvent(Unknown Source) 
at java.awt.Component.processEvent(Unknown Source) 
at java.awt.Container.processEvent(Unknown Source) 
at java.awt.Component.dispatchEventImpl(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Window.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
at java.awt.EventQueue.access$500(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue.dispatchEvent(Unknown Source) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.run(Unknown Source) 

編輯: 我改變了selectExcelFile()方法到這一點:

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 
    File newFile = null; 

    if(columnsQuery != null) { 
     try { 
      excelFileName = eUtil.getFile(FileExtensions.XLS); 

      if(excelFileName != null) { 

       newFile = new File(excelFileName); 

       if(newFile.exists()) { 
        try { 
         workbook = WorkbookFactory.create(newFile); 
        } catch (EncryptedDocumentException | InvalidFormatException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 
       else { 
        if (newFile.getName().endsWith(".xls")) { 
         workbook = new HSSFWorkbook(); 
        } 
        else if (newFile.getName().endsWith(".xlsx")) { 
         workbook = new XSSFWorkbook(); 
        } 
        else { 
         throw new IllegalArgumentException("Must be .xls or .xlsx"); 
        } 
       } 

       excelFileIn = new FileInputStream(newFile); 
       exportColsToWorkbook(columnsQuery); 

       excelFileOut = new FileOutputStream(newFile); 
       workbook.write(excelFileOut); 

       // close everything 
       workbook.close(); 
       excelFileIn.close(); 
       excelFileOut.close(); 
      } 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     catch (SQLException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

寫作工作本書的Excel文件在工作表上所謂的工作(沒有得到任何錯誤),但是當我打開Excel文件來檢查,我突然得到這樣的: enter image description here

我點擊確定,這只是空的。沒有工作表或工作簿。

因此,這解釋了爲什麼我下次運行該程序並嘗試在同一個Excel文件上編寫工作簿時出現此錯誤。

Exception in thread "AWT-EventQueue-0" org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long) 
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:216) 
at org.apache.poi.poifs.filesystem.NPOIFSFileSystem.<init>(NPOIFSFileSystem.java:166) 
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:278) 
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:250) 
at org.apache.poi.ss.usermodel.WorkbookFactory.create(WorkbookFactory.java:229) 
at mhhls.him.dbtoexcel.program.DBtoExcel.selectExcelFile(DBtoExcel.java:205) 
at mhhls.him.dbtoexcel.program.DBtoExcel.exportToExcel(DBtoExcel.java:487) 
at mhhls.him.dbtoexcel.ui.main.DBtoExcelWindow$7.actionPerformed(DBtoExcelWindow.java:190) 
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) 
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) 
at javax.swing.DefaultButtonModel.setPressed(Unknown Source) 
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) 
at java.awt.Component.processMouseEvent(Unknown Source) 
at javax.swing.JComponent.processMouseEvent(Unknown Source) 
at java.awt.Component.processEvent(Unknown Source) 
at java.awt.Container.processEvent(Unknown Source) 
at java.awt.Component.dispatchEventImpl(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) 
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) 
at java.awt.Container.dispatchEventImpl(Unknown Source) 
at java.awt.Window.dispatchEventImpl(Unknown Source) 
at java.awt.Component.dispatchEvent(Unknown Source) 
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) 
at java.awt.EventQueue.access$500(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.awt.EventQueue$3.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.awt.EventQueue$4.run(Unknown Source) 
at java.security.AccessController.doPrivileged(Native Method) 
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source) 
at java.awt.EventQueue.dispatchEvent(Unknown Source) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) 
at java.awt.EventDispatchThread.run(Unknown Source) 

我只是不明白爲什麼它會在我試圖將工作簿寫入新工作表時損壞Excel文件。

回答

2

您似乎錯過了一些關鍵代碼行。但是,假設你正在做的事情,如:

File newFile = new File("output.xlsx"); 
if (!newFile.exists) { newFile.createNewFile(); } 
Workbook wb = WorkbookFactory.create(newFile); 

然後這是不行的

您只能使用WorkbookFactory加載預先存在的Excel文件。您不能使用WorkbookFactory來創建一個全新的空白工作簿。非常相關,你也不能做new HSSFWorkbook(emptyStream)new HSSFWorkbook(emptyFile),如果從InputStreamFile創建一個*SSFWorkbook那麼必須存在並被填充。

相反,如果你想創建一個全新的空工作簿中,你需要做的更像是:

Workbook wb; 
File newFile = new File("output.xlsx"); 
if (newFile.exists) { 
    // Load existing 
    wb = WorkbookFactory.create(newFile); 
} else { 
    // What kind of file are they trying to ask for? 
    // Add additional supported types here 
    if (newFile.getName().endsWith(".xls")) { 
     wb = new HSSFWorkbook(); 
    } 
    else if (newFile.getName().endsWith(".xlsx")) { 
     wb = new XSSFWorkbook(); 
    } 
    else { 
     throw new IllegalArgumentException("I don't know how to create that kind of new file"); 
    } 
} 

對於全新的空文件,你需要決定要創建什麼類型的文件,然後新的合適的*SSFWorkbook實例沒有流/文件傳入

+0

我沒有使用WorkbookFactory。我已編輯它以添加缺少的代碼。 – PuggyLongLegs

+0

同樣的事情適用 - 如果你給一個文件或一個流,那麼它必須存在,並且其中的內容 – Gagravarr

+0

「無效頭標記;讀取0x0000000000000000」 - 這是否意味着該文件不存在? – PuggyLongLegs