java處理Excel文件---excel文件的創建,刪除,寫入,讀取
這篇文章的代碼是我封裝的excel處理類,包括判斷excel是否存在,表格索引是否存在,創建excel文件,刪除excel文件,往 excel中寫入信息,從excel中讀取數據。尤其在寫入與讀取兩個方法中,我采用了java反射機制去實現,以object對象作為參數即可,代碼自 動解析該實體類的屬性與方法,代碼重用性高。
代碼還有一些需要改進和擴展的地方,大家可以根據實際情況進行簡單修改。
上代碼,首先是我封裝的這個類(采用的是POI包):
package module.system.common;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; 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; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; /** * 從excel讀取數據/往excel中寫入 excel有表頭,表頭每列的內容對應實體類的屬性 * * @author nagsh * */ public class ExcelManage { private HSSFWorkbook workbook = null; /** * 判斷文件是否存在. * @param fileDir 文件路徑 * @return */ public boolean fileExist(String fileDir){ boolean flag = false; File file = new File(fileDir); flag = file.exists(); return flag; } /** * 判斷文件的sheet是否存在. * @param fileDir 文件路徑 * @param sheetName 表格索引名 * @return */ public boolean sheetExist(String fileDir,String sheetName){ boolean flag = false; File file = new File(fileDir); if(file.exists()){ //文件存在 //創建workbook try { workbook = new HSSFWorkbook(new FileInputStream(file)); //添加Worksheet(不添加sheet時生成的xls文件打開時會報錯) HSSFSheet sheet = workbook.getSheet(sheetName); if(sheet!=null) flag = true; } catch (Exception e) { e.printStackTrace(); } }else{ //文件不存在 flag = false; } return flag; } /** * 創建新excel. * @param fileDir excel的路徑 * @param sheetName 要創建的表格索引 * @param titleRow excel的第一行即表格頭 */ public void createExcel(String fileDir,String sheetName,String titleRow[]){ //創建workbook workbook = new HSSFWorkbook(); //添加Worksheet(不添加sheet時生成的xls文件打開時會報錯) Sheet sheet1 = workbook.createSheet(sheetName); //新建文件 FileOutputStream out = null; try { //添加表頭 Row row = workbook.getSheet(sheetName).createRow(0); //創建第一行 for(int i = 0;i < titleRow.length;i++){ Cell cell = row.createCell(i); cell.setCellValue(titleRow[i]); } out = new FileOutputStream(fileDir); workbook.write(out); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 刪除文件. * @param fileDir 文件路徑 */ public boolean deleteExcel(String fileDir){ boolean flag = false; File file = new File(fileDir); // 判斷目錄或文件是否存在 if (!file.exists()) { // 不存在返回 false return flag; } else { // 判斷是否為文件 if (file.isFile()) { // 為文件時調用刪除文件方法 file.delete(); flag = true; } } return flag; } /** * 往excel中寫入(已存在的數據無法寫入). * @param fileDir 文件路徑 * @param sheetName 表格索引 * @param object */ public void writeToExcel(String fileDir,String sheetName, Object object){ //創建workbook File file = new File(fileDir); try { workbook = new HSSFWorkbook(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //流 FileOutputStream out = null; HSSFSheet sheet = workbook.getSheet(sheetName); // 獲取表格的總行數 int rowCount = sheet.getLastRowNum() + 1; // 需要加一 // 獲取表頭的列數 int columnCount = sheet.getRow(0).getLastCellNum(); try { Row row = sheet.createRow(rowCount); //最新要添加的一行 //通過反射獲得object的字段,對應表頭插入 // 獲取該對象的class對象 Class class_ = object.getClass(); // 獲得表頭行對象 HSSFRow titleRow = sheet.getRow(0); if(titleRow!=null){ for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { //遍歷表頭 String title = titleRow.getCell(columnIndex).toString().trim().toString().trim(); String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大寫; String methodName = "get"+UTitle; Method method = class_.getDeclaredMethod(methodName); // 設置要執行的方法 String data = method.invoke(object).toString(); // 執行該get方法,即要插入的數據 Cell cell = row.createCell(columnIndex); cell.setCellValue(data); } } out = new FileOutputStream(fileDir); workbook.write(out); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 讀取excel表中的數據. * * @param fileDir 文件路徑 * @param sheetName 表格索引(EXCEL 是多表文檔,所以需要輸入表索引號,如sheet1) * @param object object */ public List readFromExcel(String fileDir,String sheetName, Object object) { //創建workbook File file = new File(fileDir); try { workbook = new HSSFWorkbook(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } 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; // 需要加一 System.out.println("rowCount:"+rowCount); 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(); //判斷文件是否存在 System.out.println(em.fileExist("E:/test2.xls")); //創建文件 String title[] = {"id","name","password"}; em.createExcel("E:/test2.xls","sheet1",title); //判斷sheet是否存在 System.out.println(em.sheetExist("E:/test2.xls","sheet1")); //寫入到excel User user = new User(); user.setId(5); user.setName("qwer"); user.setPassword("zxcv"); User user3 = new User(); user3.setId(6); user3.setName("qwerwww"); user3.setPassword("zxcvwww"); em.writeToExcel("E:/test2.xls","sheet1",user); em.writeToExcel("E:/test2.xls","sheet1",user3); //讀取excel User user2 = new User(); List list = em.readFromExcel("E:/test2.xls","sheet1", user2); for (int i = 0; i < list.size(); i++) { User newUser = (User) list.get(i); System.out.println(newUser.getId() + " " + newUser.getName() + " " + newUser.getPassword()); } //刪除文件 //System.out.println(em.deleteExcel("E:/test2.xls")); } } </pre>
下面是用于測試的一個bean類:package module.system.common;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; } } </pre>
注意:在創建excel時,需要傳入一個包含表頭信息的數組,該數組中的內容必須對應bean類的屬性值(數量可以不一樣,但拼寫和大小寫必須一致)
來自:http://blog.csdn.net/u012116457/article/details/46325245
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!