運用java的監聽模式封裝excel的讀取

運用android listener監聽模式設計excel的讀取java

熟悉java開發的人想必不會對監聽模式陌生,在android的應用層的設計中,廣泛採用這種監聽模式(點擊事件、Touch事件等)android

本人最近研究android sdk源代碼發現這是一種對api很好的封裝的模式,您在寫接口或是工具類時運用這種模式會有意想不到的收穫。apache

現學現用我運用這種模式對讀取excel的類進行了封裝,簡單的封裝了一個通用的excel讀取類。api


一、首先聲明一個監聽接口,接口中定義getData方法用於得到數據數組

package com.excel;

public interface ExcelDataListener {
	/**
	 * 得到excel數據
	 * @param data 得到excel內容
	 * @param sheet excel文檔的sheet
	 */
	public abstract void getData(String data, String sheet);
}

二、實現excel文檔讀取類ide

package com.excel;
import java.io.IOException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * 操做Excel表格的功能類
 * 讀取excel2003
 * @version 1.0
 */
public class ExcelReader2003 {
	private POIFSFileSystem fs;
	private HSSFWorkbook wb;
	private HSSFSheet sheet;
	private HSSFRow row;
	private ExcelDataListener mListener;  //聲明監聽事件變量
	
	public void setDataListener(ExcelDataListener l){  //設置監聽
		mListener = l;
	}
	
	
	/**
	 * 讀取Excel表格表頭的內容
	 * 
	 * @param InputStream
	 * @return String 表頭內容的數組
	 * 
	 */
	public String[] readExcelTitle(InputStream is) {
		try {
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (IOException e) {
			e.printStackTrace();
		}
		sheet = wb.getSheetAt(0);
		row = sheet.getRow(0);
		// 標題總列數
		int colNum = row.getPhysicalNumberOfCells();
		String[] title = new String[colNum];
		for (int i = 0; i < colNum; i++) {
			title[i] = getStringCellValue(row.getCell((short) i));
		}
		return title;
	}

	/**
	 * 讀取Excel數據內容
	 * 
	 * @param InputStream
	 * @return Map 包含單元格數據內容的Map對象
	 */
	public Map<Integer, String> readExcelContent(InputStream is) {
		Map<Integer, String> content = new HashMap<Integer, String>();
		try {
			fs = new POIFSFileSystem(is);
			wb = new HSSFWorkbook(fs);
		} catch (IOException e) {
			e.printStackTrace();
		}
		for (int k = 0; k < wb.getNumberOfSheets(); k++) {
			String str = "";
			sheet = wb.getSheetAt(k);
			// 獲得總行數
			int rowNum = sheet.getLastRowNum();
			// 正文內容應該從第二行開始,第一行爲表頭的標題
			for (int i = 0; i <= rowNum; i++) {
				row = sheet.getRow(i);
				if (row == null)
					continue;
				int colNum = row.getPhysicalNumberOfCells();
				int j = 0;
				while (j < colNum) {
					// 每一個單元格的數據內容用"-"分割開,之後須要時用String類的replace()方法還原數據
					// 也能夠將每一個單元格的數據設置到一個javabean的屬性中,此時須要新建一個javabean
					str += getStringCellValue(row.getCell((short) j)).trim()
							+ "-";
					j++;
				}
				mListener.getData(str, "sheet"+k);         //觸發監聽事件
				content.put(i, str);
				str = "";
			}
		}
		return content;
	}

	/**
	 * 獲取單元格數據內容爲字符串類型的數據
	 * 
	 * @param cell
	 *            Excel單元格
	 * @return String 單元格數據內容
	 */
	private String getStringCellValue(HSSFCell cell) {
		if(cell == null)
			return"";
		String strCell = "";
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_STRING:
			strCell = cell.getStringCellValue();
			break;
		case HSSFCell.CELL_TYPE_NUMERIC:
			strCell = String.valueOf(cell.getNumericCellValue());
			break;
		case HSSFCell.CELL_TYPE_BOOLEAN:
			strCell = String.valueOf(cell.getBooleanCellValue());
			break;
		case HSSFCell.CELL_TYPE_BLANK:
			strCell = "";
			break;
		default:
			strCell = "";
			break;
		}
		if (strCell.equals("") || strCell == null) {
			return "";
		}
		if (cell == null) {
			return "";
		}
		return strCell;
	}

	/**
	 * 獲取單元格數據內容爲日期類型的數據
	 * 
	 * @param cell
	 *            Excel單元格
	 * @return String 單元格數據內容
	 */
	private String getDateCellValue(HSSFCell cell) {
		String result = "";
		try {
			int cellType = cell.getCellType();
			if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
				Date date = cell.getDateCellValue();
				result = (date.getYear() + 1900) + "-" + (date.getMonth() + 1)
						+ "-" + date.getDate();
			} else if (cellType == HSSFCell.CELL_TYPE_STRING) {
				String date = getStringCellValue(cell);
				result = date.replaceAll("[年月]", "-").replace("日", "").trim();
			} else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
				result = "";
			}
		} catch (Exception e) {
			System.out.println("日期格式不正確!");
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 得到Excel表中的內容
	 * 
	 * @param args
	 *@return
	 * @author zcg 2012-12-15
	 */
	public Map<Integer, String> getContent(String path) {
		Map<Integer, String> map = null;
		try {
			// 對讀取Excel表格內容測試
			InputStream is2 = new FileInputStream(path);
			map = readExcelContent(is2);
		} catch (FileNotFoundException e) {
			System.out.println("未找到指定路徑的文件!");
			e.printStackTrace();
		}
		return map;
	}

	public String[] getTitle(String path) {
		String[] title = null;
		try {
			// 對讀取Excel表格標題測試
			InputStream is = new FileInputStream(path);
			ExcelReader2003 excelReader = new ExcelReader2003();
			title = excelReader.readExcelTitle(is);
			/*
			 * System.out.println("得到Excel表格的標題:"); for (String s : title) {
			 * System.out.print(s + " "); }
			 */
		} catch (FileNotFoundException e) {
			System.out.println("未找到指定路徑的文件!");
			e.printStackTrace();
		}
		return title;

	}
}

在此類中X行聲明瞭ExcelDataListener的對象mListener;函數

關鍵在X行工具

mListener.getData(str, "sheet"+k);         //觸發監聽事件測試

觸發監聽函數。也就是說沒讀取excel中的一行數據就會觸發本類中須要實現的getData函數。設計

三、測試類

package com.excel;

public class Test {
	private static String path = "D:\\ss.xls";
	public static void main(String args[]){
		ExcelReader2003 er = new ExcelReader2003();
		er.setDataListener(new ExcelDataListener() { //設置監聽事件 
			@Override
			public void getData(String data, String sheet) {
				System.out.println(sheet+data); //獲得返回的excel中每行的數據
			}
		});
		er.getContent(path); 
	}

}
相關文章
相關標籤/搜索