2014-02-24 126 views
4

我在Excel中有一個文檔,我想使用java編輯或輸入數據..我嘗試過,但我可以做的只是刪除我的Excel中的數據,並將其替換爲我剛剛輸入的數據。我正在使用Netbeans作爲我的編譯器。我的輸出是GUI/JFrame 如何將數據插入到特定的列,行和表? 例如,我想將其插入到C12,E11,工作表Sheet1等Apache POI - 將數據插入到特定的列/行和表中EXCEL w/Java

謝謝...

我做自學只在Java編碼,這就是爲什麼我不知道多少..

回答

5

這是XLS不XLSX只是例子。你可以參考here。如果您想在xlsx中編輯/輸入數據(您可以使用XSSFWorkbook和XSSFSheet)。

try { 
     //Get the excel file. 
     FileInputStream file = new FileInputStream(new File("(which sheet you want to modify or edit(put the path here)")); 

     //Get workbook for XLS file. 
     HSSFWorkbook yourworkbook = new HSSFWorkbook(file); 

     //Get first sheet from the workbook. 
     //If there have >1 sheet in your workbook, you can change it here IF you want to edit other sheets. 
     HSSFSheet sheet1 = yourworkbook.getSheetAt(0); 

     // Get the row of your desired cell. 
     // Let's say that your desired cell is at row 2. 
     Row row = sheet1.getRow(1); 
     // Get the column of your desired cell in your selected row. 
     // Let's say that your desired cell is at column 2. 
     Cell column = row.getCell(1); 
     // If the cell is String type.If double or else you can change it. 
     String updatename = column.getStringCellValue(); 
     //New content for desired cell. 
     updatename="Lala"; 
     //Print out the updated content. 
     System.out.println(updatename); 
     //Set the new content to your desired cell(column). 
     column.setCellValue(updatename); 
     //Close the excel file. 
     file.close(); 
     //Where you want to save the updated sheet. 
     FileOutputStream out = 
      new FileOutputStream(new File("(where you want to save?.Put the path here)")); 
     yourworkbook.write(out); 
     out.close(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
1

下面是摘錄幫助您:

public void write() throws IOException, WriteException { 
    File file = new File("file_location"); 
    WorkbookSettings wbSettings = new WorkbookSettings(); 
    wbSettings.setLocale(new Locale("en", "EN")); 
    WritableWorkbook wb= Workbook.createWorkbook(file, wbSettings); 
    wb.createSheet("My Spreadsheet", 0); 
    WritableSheet excel = wb.getSheet(0); 
    createLabel(excel); 
    createContent(excel); 
    wb.write(); 
    wb.close(); 
} 
相關問題