2013-10-13 31 views
0

我玩弄了jexcel libary閱讀Excel工作表中,並處理和輸出它

我試圖編寫一個小程序,它具有以下功能:

  1. 讀取一個xls文件
  2. 使在片少許computaitons並將其寫入到另一個地方

公共類數據處理器{

private String inputFile; 
    private String outputFile; 



private Sheet sheet; 
    private Workbook w; 

    public void setInputFile(String inputFile) { 
     this.inputFile = inputFile; 
    } 

    public void setOutputFile(String outputFile) { 
     this.outputFile = outputFile; 
    } 

    public void read() throws IOException { 
     File inputWorkbook = new File(inputFile); 
     Workbook w; 
     try { 
      w = Workbook.getWorkbook(inputWorkbook); 
      sheet = w.getSheet(0); 
     } catch (BiffException e) { 
      e.printStackTrace(); 
     } 
    } 

    @SuppressWarnings("deprecation") 
    public void write() throws IOException, WriteException { 
     File file = new File(inputFile); 
     WorkbookSettings wbSettings = new WorkbookSettings(); 

     wbSettings.setLocale(new Locale("en", "EN")); 

     WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings); 
     workbook.createSheet("Lolonator", 0); 
     workbook.createSheet("Lolonator123", 1); 
     workbook.copy(w); 

     workbook.write(); 
     workbook.close(); 
    } 

    public static void main(String[] args) throws IOException, WriteException { 
     ReadExcel test = new ReadExcel(); 
     test.setInputFile("C:/Users/Desktop/sheet1.xls"); 
     test.read(); 
     System.out.println("####################################################"); 
     System.out.println("File read!"); 

//  Write 
     System.out.println("####################################################"); 
     System.out.println("Start to write the file!"); 
     WriteExcel out = new WriteExcel(); 
     out.setOutputFile("C:/Users/Desktop/sheet2.xls"); 
     out.write(); 
     System.out.println("Please check the result file!"); 

    } 

} 

但是,這是行不通的。即使我的程序運行到最後,我也沒有在我的工作表中得到任何輸出。我真的很感謝你的回答!

回答

1

在您的寫入函數中,您正在使用「inputFile」作爲File構造函數的參數,但是在創建out對象後沒有初始化它。

所以在寫功能

File file = new File(inputFile); 

以下行應該是

File file = new File(outputFile); 

而且你確定你沒有看到運行此代碼後,任何錯誤。它應該拋出空指針異常。

希望這會有所幫助...

+0

Thx for your answer!然而,沒有什麼改變'outputFile' ... – mrquad

+0

我看不到你的文章中的ReadExcel和WriteExcel類的主體,但不應該創建DataProcessor對象嗎?同時檢查您的文件是否在您的寫入功能中正確創建。 –

+0

您是否可以圍繞代碼在try-catch塊中調用寫入函數的位置並打印出異常。它會給你造成問題的原因(找不到文件,未找到路徑等)。 –