天天看點

java讀取excel并操作資料

java中使用poi開放的api來操作excel中的資料

官網:http://poi.apache.org/

寫了一個java excel的demo,代碼如下;

package com.lc_kykz.test;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.StringTokenizer;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/*
 * @Author : Gavin
 * @Function: 讀取excel并操作資料
 * @Date : 2015-6-18
 */
public class ExcelReader {
	// 建立檔案輸入流
	private BufferedReader reader = null;
	// 檔案類型
	private String filetype;
	// 檔案二進制輸入流
	private InputStream is = null;
	// 目前的Sheet
	private int currSheet;
	// 目前位置
	private int currPosition;
	// Sheet數量
	private int numOfSheets;
	// HSSFWorkbook
	HSSFWorkbook workbook = null;
	// 設定Cell之間以空格分割
	private static String EXCEL_LINE_DELIMITER = ",";

	// 構造函數建立一個ExcelReader
	public ExcelReader(String inputfile) throws IOException, Exception {
		// 判斷參數是否為空或沒有意義
		if (inputfile == null || inputfile.trim().equals("")) {
			throw new IOException("NO input file!!!");
		}
		// 取得檔案名的字尾名指派給filetype
		filetype = inputfile.substring(inputfile.lastIndexOf(".") + 1);
		
		// 設定開始行為0
		currPosition = 0;
		// 設定目前位置為0
		currSheet = 0;
		// 建立檔案輸入流
		is = new FileInputStream(inputfile);
		
		// 判斷檔案格式
		if (filetype.equalsIgnoreCase("xls")) {
			// 如果是Excel檔案則建立HSSFWorkbook讀取
			workbook = new HSSFWorkbook(is);
			// 設定Sheet數
			numOfSheets = workbook.getNumberOfSheets();
		} else {
			throw new Exception("File Type incorrrect!");
		}
	}

	// 用于讀取檔案的一行
	public String readLine() throws IOException {
		// excel檔案通過poi讀取檔案
		if (filetype.equalsIgnoreCase("xls")) {
			// 根據currSheet值獲得目前的sheet
			HSSFSheet sheet = workbook.getSheetAt(currSheet);
			
			// 判斷目前行是否到但前Sheet的結尾
			if (currPosition > sheet.getLastRowNum()) {
				// 目前行位置清零
				currPosition = 0;
				// 判斷是否還有Sheet
				while (currSheet < numOfSheets - 1) {
					// 得到下一張Sheet
					currSheet += 1;
					sheet = workbook.getSheetAt(currSheet);
					
					// 目前行數是否已經到達檔案末尾
					if (currPosition > sheet.getLastRowNum()) {
						// 目前Sheet指向下一張Sheet
						currSheet++;
						continue;
					} else {
						// 擷取目前行數
						int row = currPosition;
						currPosition++;
						// 讀取目前行資料
						return getLine(sheet, row);
					}
				}
				return null;
			}
			// 擷取目前行數
			int row = currPosition;
			currPosition++;
			// 讀取目前行資料
			return getLine(sheet, row);
		}
		return null;
	}

	// 傳回Sheet的一行資料
	private String getLine(HSSFSheet sheet, int row) {
		// 根據行數取得Sheet的一行
		HSSFRow rowline = sheet.getRow(row);
		// 建立字元創緩沖區
		StringBuffer buffer = new StringBuffer();
		// 擷取目前行的列數
		int filledColumns = rowline.getLastCellNum();
		HSSFCell cell = null;
		// 循環周遊所有列
		for (int i = 0; i < filledColumns; i++) {
			// 取得目前Cell
			cell = rowline.getCell((short) i);
			String cellvalue = null;
			if (cell != null) {
				// 判斷目前Cell的Type
				switch (cell.getCellType()) {
				
					// Cell的Type為NUMERIC
					case HSSFCell.CELL_TYPE_NUMERIC: {
						// 判斷目前的cell是否為Date
						if (HSSFDateUtil.isCellDateFormatted(cell)) {
							// 如果是Date類型則,取得該Cell的Date值
							Date date = cell.getDateCellValue();
							// 把Date轉換成本地格式的字元串
							cellvalue = cell.getDateCellValue().toLocaleString();
						} else { // 如果是純數字
							// 取得目前Cell的數值,強制轉換為int
							Integer num = new Integer(
									(int) cell.getNumericCellValue());
							cellvalue = String.valueOf(num);
						}
						break;
					}
					// Cell的Type為STRING
					case HSSFCell.CELL_TYPE_STRING:
						// 取得目前的Cell字元串
						cellvalue = cell.getStringCellValue().replaceAll("'", "''");
						break;
					// 預設的Cell值
					default:
						cellvalue = " ";
					}
			} else {
				cellvalue = "";
			}
			// 在每個字段之間插入分割符
			buffer.append(cellvalue).append(EXCEL_LINE_DELIMITER);
			// 去除最後一個分隔符
			buffer.substring(0, buffer.length() - 1);
		}
		return buffer.toString();
	}

	// 關閉資源
	public void closeResource() {
		try {
			if (is != null) 
				is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if (reader != null) 
					reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}	
	}

	// 測試case
	public static void main(String[] args) {
		try {
			ExcelReader er = new ExcelReader("d://Gavin/xxx.xls");
			String line = er.readLine();
			//得到excel資料後,寫處理資料的代碼就可以了,如:插入資料庫等等
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}