jxl分割excel文件

最近在實施一個項目,其中一項工作是處理歷史數據。客戶提供過來的數據是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();
			}
		}

	}
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章