jxl分割excel檔案
阿新 • • 發佈:2019-01-28
最近在實施一個專案,其中一項工作是處理歷史資料。客戶提供過來的資料是excel表格,超過20萬條記錄,由於目標系統匯入限制,每次只能匯入大小不超過8M的檔案,所以需要對這些資料進行分割處理。在手工處理一遍後,覺得可以通過寫一個程式來自動實現分割,於是用JAVA寫了一個程式,用於針對特定檔案實現給定記錄數的分割功能。
詳見程式碼:
package cn.sean.main; import java.io.File; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; public class AccessExcel { Cell[] titleCell; Cell[][] allCell; jxl.Workbook workBook; Sheet sheet; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String url = "c:\\a.xls"; AccessExcel ae = new AccessExcel(); ae.readExcel(url); ae.splitExcel(500, "c:\\"); } /* * 讀取原excel檔案,並將相關的資料儲存到陣列中 */ public void readExcel(String source) { File file = new File(source); try { workBook = Workbook.getWorkbook(file); sheet = workBook.getSheet(0); titleCell = new Cell[sheet.getColumns()];// 用於儲存列標題 allCell = new Cell[sheet.getColumns()][sheet.getRows()];// 用於儲存所有單元格資料 // 將列標題儲存存到一個一維陣列中 for (int i = 0; i < titleCell.length; i++) { titleCell[i] = sheet.getCell(i, 0); } // 將所有單元格資料儲存到一個二維陣列中 for (int i = 0; i < sheet.getColumns(); i++) { for (int j = 0; j < sheet.getRows(); j++) { allCell[i][j] = sheet.getCell(i, j); } } } catch (BiffException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* *@param number代表需要分隔的行數 *@param destination代表分隔檔案後儲存的路徑 */ public void splitExcel(int number, String destination) { int index = (int) Math.ceil(sheet.getRows() / number);//計算需要分隔多少個檔案 File[] files = new File[index + 1]; //初始化檔案陣列 for (int i = 0; i <= index; i++) { files[i] = new File(destination + i + ".xls"); } int n = number; int y = 1;//用於記錄行的位置 for (int i = 0; i <= index; i++) { try { jxl.write.WritableWorkbook ww = Workbook .createWorkbook(files[i]); WritableSheet ws = ww.createSheet("sheet1", 0); for (int t = 0; t < sheet.getColumns(); t++) { ws.addCell(new Label(t, 0, allCell[t][0].getContents())); } out: for (int m = 1; y < sheet.getRows(); y++, m++) { for (int x = 0; x < sheet.getColumns(); x++) { if (y >number) { number += n; break out; } ws.addCell(new Label(x, m, allCell[x][y].getContents())); } } ww.write(); ww.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RowsExceededException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }