標籤:
如果直接把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方法參數為Stringmethod.invoke(obj, data); // 執行該方法} else if (fieldTypes[columnIndex].equals("int")) {method = class_.getDeclaredMethod(methodName,int.class); // 設定要執行的方法--set方法參數為intdouble 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 qqqq2 bb wwwww3 cc eeee4 dd rrrr5 ee tttt
利用java反射機制實現讀取excel表格中的資料