POI操作EXCELファイルのシンプルパッケージ

18351 ワード

最近POIを見て、いくつかの例を書きました。反射技術を合わせてEXCELの導入を簡単にカプセル化しました。主に機能は以下の通りです。
(1)EXCEL文書をList<Map<String,String>に導入する
(2)EXCELにList<Map<String、String>タイプデータをエクスポートする
(3)List<Object>タイプのデータをEXCELにエクスポートする
このうち、(3)番目の方法は、対応するフォーマット仕様の反射を使用しており、具体的には、Listにおけるオブジェクトの取得方法名を設定すれば、大幅な多重化が可能である。
注:サポートオブジェクトの深さ導出、すなわちListに格納されているオブジェクトの値取り方法の戻り値は別のオブジェクトの参照であり、最終的に必要な値はこの参照オブジェクトの中にあります。
余计な话は言いません。コードを入れます。
POIパッケージ類(メインクラス)MyPOI.java

package com.lightgjc1.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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;

public class MyPOI {
	
	/**
	 *   Excel  
	 * 		   List<Map<String K,String V>>     
	 * @param excelFile	:	Excel    
	 * @param strKeys	:	Map Key  ,Value    sheet       
	 * @return
	 */
	public static List<Map<String,String>> importExcelToMap(File excelFile, String strKeys) {
		String[] strKey = strKeys.split(",");
		List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
		
		int i = 1;
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelFile));
			HSSFSheet sheet = workbook.getSheetAt(0);
			while (true) {
				HSSFRow row = sheet.getRow(i);
				if (row == null)
					break;
				
				Map<String,String> map = new HashMap<String,String>();
				for(int keyIndex = 0; keyIndex < strKey.length; keyIndex++){
					map.put(strKey[keyIndex], row.getCell(keyIndex).getStringCellValue());
				}
				listMap.add(map);
				
				i++;
			}
		} catch (Exception e) {
			e.printStackTrace();
			
			System.out.println("    ,    : "+ i +"   !");
		}
		
		return listMap;
	}
	
	/**
	 *   Excel  
	 * 		         List<Map<String K,String V>>
	 * @param objList	:	Excel   
	 * @param title		:	  Sheet   
	 * @param strTitle	:	Sheet     (        )
	 * @param strBody	:	Sheet        (     objClass get    )
	 * @param outputPath:	Excel      
	 */
	public static void exportExcelByMap(List<Map<String,String>> objList, String title, String strTitle, String strBody, String outputPath) {
		//      (Excel  )
		HSSFWorkbook workbook = new HSSFWorkbook();
		
		//   Excel       Sheet 
		HSSFSheet sheet = workbook.createSheet(title);
		
		//   Sheet     (   )
		createTitle(sheet, strTitle);
		
		//   Sheet     (   )
		String[] strArray = strBody.split(",");
		for(int objIndex = 0; objIndex < objList.size(); objIndex++) {
			Map map = objList.get(objIndex);
			HSSFRow row = sheet.createRow(objIndex + 1); 
			for(int i = 0; i < strArray.length; i++) {
				HSSFCell cell = row.createCell(i);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(map.get(strArray[i]).toString());
			}
		}
		
		//   Excel  
		saveExcelFile(workbook, outputPath);
	}
	
	/**
	 *   Excle  
	 * 
	 * @param objList	:	Excel   
	 * @param objClass	:	Excel         
	 * @param title		:	  Sheet   
	 * 				ex:	title = "   ";
	 * @param strTitle	:	Sheet     (        )
	 * 				ex:	strTitle = "    ,    ,  ,    ,  ,    ,    ,    ,   ";
	 * @param strBody	:	Sheet        (     objClass get    )
	 * 				ex:	strBody = "getCode,getName,getSex,getBirthday,getHomeplace.getName,getOrg.getShortName,getContactTel,getEmail,getZjm";
	 * @param outputPath:	Excel      
	 */
	public static void exportExcelByObject(List objList, Class objClass, String title, String strTitle, String strBody, String outputPath) {
			//       
			HSSFWorkbook workbook = initWorkbook(objList, objClass, title, strTitle, strBody);
			//   Excel  
			saveExcelFile(workbook, outputPath);
	}
	/**
	 *       
	 * 
	 * @param objList	:	Excel   
	 * @param objClass	:	Excel         
	 * @param title		:	  Sheet   
	 * @param strTitle	:	Sheet     (        )
	 * @param strBody	:	Sheet        (     objClass get    )
	 */
	private static HSSFWorkbook initWorkbook(List objList, Class objClass, String title, String strTitle, String strBody){
		//      (Excel  )
		HSSFWorkbook workbook = new HSSFWorkbook();
		
		//   Excel       Sheet 
		HSSFSheet sheet = workbook.createSheet(title);
		
		//   Sheet     (   )
		createTitle(sheet, strTitle);
		
		//   Sheet     (   )
		createBody(objList, objClass, sheet, strBody);
		
		return workbook;
	}
	
	/**
	 *   Excel  sheet     
	 * 
	 * @param sheet		:	Excel      sheet
	 * @param strTitle	:	sheet     (sheet      )
	 */
	private static void createTitle(HSSFSheet sheet, String strTitle){
		HSSFRow row = sheet.createRow(0); //        
		HSSFCell cell = null;
		
		String[] strArray = strTitle.split(",");
		
		for(int i = 0; i < strArray.length; i++) {
			cell = row.createCell(i); //        
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(strArray[i]);
		}
		
	}
	
	/**
	 *   Excel  sheet     
	 * 
	 * @param objList	:	Excel   
	 * @param objClass	:	Excel         
	 * @param sheet		:	Excel    sheet 
	 * @param strBody	:	Sheet        (     objClass get    )
	 */
	private static void createBody(List objList, Class objClass, HSSFSheet sheet, String strBody){
		String[] targetMethod = strBody.split(",");
		Method[] ms = objClass.getMethods();
		
		//   objList    (  sheet  )
		for(int objIndex = 0; objIndex < objList.size(); objIndex++){
			Object obj = objList.get(objIndex);
			HSSFRow row = sheet.createRow(objIndex + 1);
			//   strBody      (  sheet  )
			for(int strIndex = 0; strIndex < targetMethod.length; strIndex++) {
				String targetMethodName = targetMethod[strIndex];
				//   ms    ,      (strBody      )   
				for(int i = 0; i < ms.length; i++) {
					Method srcMethod = ms[i];
					int len = targetMethodName.indexOf(".") < 0 ? targetMethodName.length() : targetMethodName.indexOf(".");
					if (srcMethod.getName().equals(targetMethodName.substring(0, len))) {
						HSSFCell cell = row.createCell(strIndex);
						cell.setCellType(HSSFCell.CELL_TYPE_STRING);
						try {
							//               
							if (targetMethodName.contains(".")) {
								cell.setCellValue(referenceInvoke(targetMethodName, obj));
							//             
							} else {
								cell.setCellValue((srcMethod.invoke(obj)).toString());
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		
	}
	
	/**
	 *              ( :getHomeplace.getName       )
	 * 		                     
	 * 
	 * @param targetMethod	:	obj         
	 * @param obj			:	      
	 * @return
	 */							//getHomeplace.getName   emp(obj)
	private static String referenceInvoke(String targetMethod, Object obj) {						
		//             (     obj     :getHomeplace())
		String refMethod = targetMethod.substring(0, targetMethod.indexOf("."));
		//         (getName())
		targetMethod = targetMethod.substring(targetMethod.indexOf(".") + 1);
		try {
			//             ( obj       :obj.getHomeplace())
			obj = obj.getClass().getMethod(refMethod).invoke(obj);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		//             
		if (targetMethod.contains(".")) {
			return referenceInvoke(targetMethod, obj);
		//             
		} else {
			try {
				//   obj                  
				Method tarMethod = obj.getClass().getMethod(targetMethod);
				return tarMethod.invoke(obj).toString();
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		
	}
	
	/**
	 *   Excel  
	 * 
	 * @param workbook	:	Excel   
	 * @param outputPath:	Excel      
	 */
	private static void saveExcelFile(HSSFWorkbook workbook, String outputPath) {
		try {
			FileOutputStream fos = new FileOutputStream(outputPath);
			workbook.write(fos);
			
			fos.flush();
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
テストクラスPOITest.java

package com.lightgjc1.test;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import junit.framework.TestCase;

import com.lightgjc1.domain.Area;
import com.lightgjc1.domain.Employee;
import com.lightgjc1.domain.OrgType;
import com.lightgjc1.domain.Organization;
import com.lightgjc1.poi.MyPOI;

public class POITest extends TestCase {
	public void testImportAndExportExcel(){
		String strKeys = "setCode,setName,setSex,setBirthday,setHomeplace,setOrg,setContactTel";
		List<Map<String,String>> listMap = MyPOI.importExcelToMap(new File("D:\\employee.xls"), strKeys);
		
		String[] keys = strKeys.split(",");
		for(Map map : listMap) {
			for(int i = 0; i < keys.length; i++) {
				System.out.print(map.get(keys[i]) +" ");
			}
			System.out.println();
			System.out.println("----------------");
		}
		
		String title = "   ";
		String strTitle = "    ,    ,  ,    ,  ,    ,    ";
		String strBody = "setCode,setName,setSex,setBirthday,setHomeplace,setOrg,setContactTel";
		String outputPath = "D:\\employee2.xls";
		MyPOI.exportExcelByMap(listMap, title, strTitle, strBody, outputPath);
	}
	
	public void testExportExcel(){
		List objList = initData();
		Class objClass = Employee.class;
		String title = "   ";
		String strTitle = "    ,    ,  ,    ,  ,    ,    ";
		String strBody = "getCode,getName,getSex,getBirthday,getHomeplace.getName,getOrg.getShortName,getOrg.getOrgType.getName";
		String outputPath = "D:\\employee.xls";
		
		MyPOI.exportExcelByObject(objList, objClass, title, strTitle, strBody, outputPath);
	}
	
	private List initData(){
		List empList = new ArrayList();
		
		Employee emp = null;
		for(int i = 0; i < 10; i++) {
			emp = new Employee();
			emp.setCode(i +" ");
			emp.setName(i +" ");
			emp.setSex(i % 2 == 0 ? " " : " ");
			emp.setBirthday(new Date());
			
			
			Area area = new Area();
			area.setName(i +" ");
			emp.setHomeplace(area);
			
			
			OrgType orgType = new OrgType();
			orgType.setName("    "+ i);
			
			Organization org = new Organization();
			org.setOrgType(orgType);
			org.setShortName("  "+ i);
			
			emp.setOrg(org);
			
			
			empList.add(emp);
		}
		
		return empList;
	}
}
その他のツール類(データを格納するエンティティ類)
Employee.java
従業員データを保管するために使用します。

package com.lightgjc1.domain;

import java.util.Date;

public class Employee {

	private String id;
	
	private String code;
	
	private String name;
	
	private String sex;
	
	private Date birthday;
	
	private String email;
	
	private String contactTel;
	
	private String zjm;
	
	private Organization org = new Organization();
	
	private Area homeplace;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getContactTel() {
		return contactTel;
	}

	public void setContactTel(String contactTel) {
		this.contactTel = contactTel;
	}

	public String getZjm() {
		return zjm;
	}

	public void setZjm(String zjm) {
		this.zjm = zjm;
	}

	public Organization getOrg() {
		return org;
	}

	public void setOrg(Organization org) {
		this.org = org;
	}

	public Area getHomeplace() {
		return homeplace;
	}

	public void setHomeplace(Area homeplace) {
		this.homeplace = homeplace;
	}
	
	
}
Organization.java
従業員が所属する組織部門を預かります。

package com.lightgjc1.domain;

import java.util.Set;

public class Organization {

	private String id;
	
	private String code;
	
	private String fullName;
	
	private String shortName;
	
	private String manager;
	
	private String desc;

	//*-----1
	private OrgType orgType;
	
	//*-----1
	private Organization parent;
	
	//1-----*
	private Set<Organization> children; 
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName = fullName;
	}

	public String getShortName() {
		return shortName;
	}

	public void setShortName(String shortName) {
		this.shortName = shortName;
	}

	public String getManager() {
		return manager;
	}

	public void setManager(String manager) {
		this.manager = manager;
	}

	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public OrgType getOrgType() {
		return orgType;
	}

	public void setOrgType(OrgType orgType) {
		this.orgType = orgType;
	}

	public Organization getParent() {
		return parent;
	}

	public void setParent(Organization parent) {
		this.parent = parent;
	}

	public Set<Organization> getChildren() {
		return children;
	}

	public void setChildren(Set<Organization> children) {
		this.children = children;
	}
	
}
OrgType.java
従業員の所属組織部門を保管する部門のタイプ

package com.lightgjc1.domain;

public class OrgType {

	private String id;
	
	//            ,       
	//private Integer id;
	//private int id;
	
	private String code;
	
	private String name;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}
アーア.java
従業員の出身地情報を保管するために使用します。

package com.lightgjc1.domain;

import java.util.Set;

public class Area {

	private String id;
	
	private String code;
	
	private String name;
	
	private Area parent;
	
	private Set<Area> children;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Area getParent() {
		return parent;
	}

	public void setParent(Area parent) {
		this.parent = parent;
	}

	public Set<Area> getChildren() {
		return children;
	}

	public void setChildren(Set<Area> children) {
		this.children = children;
	}
	
}