1. 程式人生 > >jxl切割excel文件

jxl切割excel文件

table 初始化 實現 ram create code ont split ace

近期在實施一個項目。當中一項工作是處理歷史數據。

客戶提供過來的數據是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();
		}

	}

	/*
	 [email protected]
/* */ number代表須要分隔的行數 [email protected] 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(); } } } }




jxl切割excel文件