目標是在別的地方找到了一串 key,要在 Excel 裡面把對應的 Row 刪除。
刪除的方法在 JXL 中必須要建立一個 WritableXXXXXX 的物件,才能夠做刪除的動作
但是 JXL 並沒有從現有的 Excel 取得 WritableWorkbook 的方法,因此只能用另一種間接的方法
即把現有的 Excel 複製出來變成另一個新的 Excel 檔,然後變成 WritableWorkbook。
範例程式碼如下:
public void removeRowInExcel (File excelFile, File newExcelFile) {
Workbook workbook = null;
WritableWorkbook wWorkbook = null;
try {
// Read the existing Excel file.
workbook = Workbook.getWorkbook(excelFile);
// Duplicate the existing Excel to the new created WritableWorkbook.
wWorkbook = Workbook.createWorkbook(newExcelFile, workbook);
wWorkbook.write();
// Get the sheet from the Excel.
System.out.println("\nRead sheet.");
WritableSheet langSheet = wWorkbook.getSheet("lang");
// Search rows in the sheet.
for(int i=langSheet.getRows()-1 ; i>=0 ; i--) {
Cell[] cells = langSheet.getRow(i);
if(cells != null && cells.length > 0) {
String keyName = cells[0].getContents();
System.out.print("Get row " + keyName + "\t");
if(keyName != null) {
keyName = keyName.trim();
// Remove the row if it is contained in the Map.
if(keyMap.get(keyName) != null) {
langSheet.removeRow(i);
System.out.println("(Removed)");
} else
System.out.println();
} else
System.out.println();
}
}
System.out.println("Update excel.");
wWorkbook.write();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(wWorkbook != null) wWorkbook.close();
} catch (Exception e) { e.printStackTrace(); }
if(workbook != null) workbook.close();
}
}
不過目前測試結果是...刪除不會出錯,但好像也沒有正確地把目標刪掉~
StackOverflow 也有找到有人問刪除不如預期的問題,然後目前沒看到完整的解決方法。
所以暫時先停在這,來試試看別的 Library。
續篇請參考「用 Java 處理 Microsoft Excel (2):使用 Apache Poi」
參考資料:
1、Java Excel API - A Java API to read, write, and modify Excel spreadsheets
2、Modifying existing excel using jxl
沒有留言:
張貼留言