1. 程式人生 > >利用java反射機制實現讀取excel表格中的資料

利用java反射機制實現讀取excel表格中的資料

如果直接把excel表格中的資料匯入資料庫,首先應該將excel中的資料讀取出來。

為了實現程式碼重用,所以使用了Object,而最終的結果是要獲取一個list如List<User>、List<Book>等,所以需要使用泛型機制去實現。下面會給出程式碼,可能會稍微複雜一點,但註釋很清晰,希望大家耐心閱讀。

在上程式碼之前簡單說一下思路:

        1.excel表格必須有表頭,且表頭中各列的值要與實體類的屬性相同;

        2.先讀取表頭資訊,然後獲取表頭列數,接著確定需要使用的set方法的名稱,並存到陣列中;

        3.利用反射機制,獲取object物件的屬性,通過與excel表格表頭對比,確定各個屬性的型別,存到陣列中(以excel表格中屬性的順序);

        4.遍歷除表頭行的資料,利用反射機制例項化物件,呼叫對應的set方法,方法引數通過3獲取;

上程式碼:(需要使用poi包,請自行下載)

實體類User:

public class User {
    private int id;
    private String name;
    private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
      
}
處理類:
package module.system.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

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

/**
 * 從excel讀取資料/往excel中寫入 excel有表頭,表頭每列的內容對應實體類的屬性
 * 
 * @author nagsh
 * 
 */
public class ExcelManage {
	private HSSFWorkbook workbook;

	public ExcelManage(String fileDir) {
		File file = new File(fileDir);
		try {
			workbook = new HSSFWorkbook(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 讀取excel表中的資料.
	 * 
	 * @param sheetName
	 *            表格索引(EXCEL 是多表文件,所以需要輸入表索引號,如sheet1)
	 */
	public List readFromExcel(String sheetName, Object object) {

		List result = new ArrayList();
		// 獲取該物件的class物件
		Class class_ = object.getClass();
		// 獲得該類的所有屬性
		Field[] fields = class_.getDeclaredFields();

		// 讀取excel資料
		// 獲得指定的excel表
		HSSFSheet sheet = workbook.getSheet(sheetName);
		// 獲取表格的總行數
		int rowCount = sheet.getLastRowNum() + 1; // 需要加一
		if (rowCount < 1) {
			return result;
		}
		// 獲取表頭的列數
		int columnCount = sheet.getRow(0).getLastCellNum();
		// 讀取表頭資訊,確定需要用的方法名---set方法
		// 用於儲存方法名
		String[] methodNames = new String[columnCount]; // 表頭列數即為需要的set方法個數
		// 用於儲存屬性型別
		String[] fieldTypes = new String[columnCount];
		// 獲得表頭行物件
		HSSFRow titleRow = sheet.getRow(0);
		// 遍歷
		for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍歷表頭列
			String data = titleRow.getCell(columnIndex).toString(); // 某一列的內容
			String Udata = Character.toUpperCase(data.charAt(0))
					+ data.substring(1, data.length()); // 使其首字母大寫
			methodNames[columnIndex] = "set" + Udata;
			for (int i = 0; i < fields.length; i++) { // 遍歷屬性陣列
				if (data.equals(fields[i].getName())) { // 屬性與表頭相等
					fieldTypes[columnIndex] = fields[i].getType().getName(); // 將屬性型別放到陣列中
				}
			}
		}
		// 逐行讀取資料 從1開始 忽略表頭
		for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {
			// 獲得行物件
			HSSFRow row = sheet.getRow(rowIndex);
			if (row != null) {
				Object obj = null;
				// 例項化該泛型類的物件一個物件
				try {
					obj = class_.newInstance();
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				// 獲得本行中各單元格中的資料
				for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
					String data = row.getCell(columnIndex).toString();
					// 獲取要呼叫方法的方法名
					String methodName = methodNames[columnIndex];
					Method method = null;
					try {
						// 這部分可自己擴充套件
						if (fieldTypes[columnIndex].equals("java.lang.String")) {
							method = class_.getDeclaredMethod(methodName,
									String.class); // 設定要執行的方法--set方法引數為String
							method.invoke(obj, data); // 執行該方法
						} else if (fieldTypes[columnIndex].equals("int")) {
							method = class_.getDeclaredMethod(methodName,
									int.class); // 設定要執行的方法--set方法引數為int
							double data_double = Double.parseDouble(data);
							int data_int = (int) data_double;
							method.invoke(obj, data_int); // 執行該方法
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				result.add(obj);
			}
		}
		return result;
	}

	public static void main(String[] args) {
		ExcelManage em = new ExcelManage("E:/test.xls");
		User user = new User();
		List list = em.readFromExcel("sheet1", user);
		for (int i = 0; i < list.size(); i++) {
			User newUser = (User) list.get(i);
			System.out.println(newUser.getId() + " " + newUser.getName() + " "
					+ newUser.getPassword());
		}

	}

}
excel表格:



執行結果:

1 aa qqqq
2 bb wwwww
3 cc eeee
4 dd rrrr
5 ee tttt