內容分多個excel檔案進行儲存資料
阿新 • • 發佈:2019-01-30
/** * 分多個excel檔案進行儲存資料 * @author hanchuang * */ public class AccessExcel { String[] titleCell; String[][] allCell; jxl.Workbook workBook; Sheet sheet; int cell; int column; /* * 將相關的資料儲存到陣列中 */ //1、列數;2、檔案內容;3、檔案路徑;4、需要分隔的行數 public void readExcel(int columns,String content,String fileurl,int number) { column=columns; String []cellname=content.substring(content.indexOf("。")).split(","); Arrays.fill(cellname,0,1,cellname[0].substring(1, cellname[0].length()));//去掉分隔符“。” cell=cellname.length/column;//---多少行資料 allCell = new String[cell][column]; //共多少條資料;多少列----- for(int i = 0 ;i<allCell.length;i++){ //初始化表格資料 for(int j = 0;j<allCell[0].length;j++){ for(int hc=(j+i*column);hc<(j+1+i*column);hc++){ allCell[i][j]=cellname[hc]; } } } titleCell=content.substring(0, content.indexOf("。")).split(",");//表頭 //將陣列內容放入excel中 splitExcel(number, fileurl); } /* *@param number代表需要分隔的行數 *@param fileurl代表分隔檔案後儲存的路徑 */ public void splitExcel(int number, String fileurl) { int index = (int) Math.ceil(cell / number);//計算需要分隔多少個檔案 File[] files = new File[index + 1]; //初始化檔案陣列 for (int i = 0; i <= index; i++) { files[i] = new File(fileurl +"("+i+")" + ".xls"); } int n = number; int y = 0;//用於記錄行的位置 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 <column; t++) { ws.addCell(new Label(t, 0, titleCell[t])); } //將陣列中的內容放入表格單元格中 out: for (int m = 1; y < cell; y++, m++) { for (int x = 0; x < column; x++) { if (y >number) { number += n; break out; } ws.addCell(new Label(x, m, allCell[y][x])); } } 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(); } } } /** * @param args */ public static void main(String[] args) { String content="count(0),處理日期,處理時間。1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9," + "1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9," + "1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,1,2,3,4,5,6,7,8,9,9,0"; AccessExcel ae = new AccessExcel(); ae.readExcel(3,content,"D:\\timingNums\\hanchuang",19); } }