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"));
	}

}

以下是用於測試的一個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;
	}

}
注意:在創建excel時,須要傳入一個包括表頭信息的數組,該數組中的內容必須相應bean類的屬性值(數量能夠不一樣,但拼寫和大寫和小寫必須一致)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM