JAva poiはexcelの生成とデータ解析を実現する


本文は主に需要に応じてexcelテンプレートを生成する方法と、excelからデータを解析して私たちが必要とする処理対象になる方法を記録し、以上の機能を実現するために、今回依存するjarパッケージは以下の通りである:poi-3.10.1.jar,poi-ooxml-3.10.1.jar.
 
Excelのすべての操作方法は、1つのツールクラスに定義され、静的メソッドとして宣言され、後で呼び出すのに便利です.
 
  • Excelの補助クラスを生成する:
  • package com.excel.util;
    
    public class ExcelModel {
    
    	/**
    	 * @Description:      excel      
    	 */
    	private String[] excelHeader;
    
    	/**
    	 * @Description: excel sheet     
    	 */
    	private String sheetName;
    
    	/**
    	 * @Description:    excel    
    	 */
    	private String fileName;
    
    	public String[] getExcelHeader() {
    		return excelHeader;
    	}
    
    	public void setExcelHeader(String[] excelHeader) {
    		this.excelHeader = excelHeader;
    	}
    
    	public String getSheetName() {
    		return sheetName;
    	}
    
    	public void setSheetName(String sheetName) {
    		this.sheetName = sheetName;
    	}
    
    	public String getFileName() {
    		return fileName;
    	}
    
    	public void setFileName(String fileName) {
    		this.fileName = fileName;
    	}
    
    }
    

     
     
  • Excelオペレーションの完全なツールクラスを定義し、呼び出しが容易:
  • package com.excel.util;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    import org.apache.poi.hssf.usermodel.HSSFFont;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellStyle;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.apache.poi.ss.usermodel.Font;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class ExcelUtil {
    
    	static final String XLS_TYPE = "XLS";
    	
    	static final String XLSX_TYPE = "XLSX";
    	
    	private ExcelUtil(){}
    	
    	/** 
    	 * @Title: createWorkbookByType 
    	 * @Description:    :           Workbook
    	 * @param type    xls  xlsx  excel  
    	 * @return
    	 * @return: Workbook
    	 * @author: zengchao   
    	 * @date: 2015 10 13    2:58:53
    	 */
    	public static Workbook createWorkbookByType(String type){
    		Workbook workbook = null;
    		if(XLS_TYPE.equals(type)){
    			workbook = new HSSFWorkbook();
    		}else if(XLSX_TYPE.equals(type)){
    			workbook = new XSSFWorkbook();
    		}
    		return workbook;
    	}
    	
    	/** 
    	 * @Title: createSheet 
    	 * @Description:    :  workbook   sheet   
    	 * @param workbook
    	 * @param sheetNo sheet   ,  workbook        
    	 * @param sheetName sheet   
    	 * @return
    	 * @return: Sheet
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:00:05
    	 */
    	public static Sheet createSheet(Workbook workbook, int sheetNo, String sheetName){
    		Sheet sheet = null;
    		if(workbook != null){
    			sheet = workbook.createSheet();
    			if(sheetName == ""||sheetName == null){
    				sheetName = "sheet" + sheetNo;
    			}
    			workbook.setSheetName(sheetNo, sheetName);
    		}
    		return sheet;
    	}
    	
    	/** 
    	 * @Title: createCellStyle 
    	 * @Description:    :  workbook    
    	 * @param workbook
    	 * @return
    	 * @return: CellStyle
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:02:48
    	 */
    	public static CellStyle createCellStyle(Workbook workbook){
    		CellStyle cellStyle = null;
    		if(workbook != null){
    			cellStyle = workbook.createCellStyle();
    			Font font = workbook.createFont();
    			font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
    			font.setColor(HSSFFont.COLOR_NORMAL);
    			cellStyle.setFont(font);
    			cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    			cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
    		}
    		return cellStyle;
    	}
    	
    	/** 
    	 * @Title: createHeader 
    	 * @Description:    :    sheet    ( :sheet    )
    	 * @param sheet
    	 * @param excelHeader
    	 * @param cellStyle
    	 * @return: void
    	 * @author: zengchao   
    	 * @date: 2015 10 13    2:59:48
    	 */
    	public static void createHeader(Sheet sheet, String[] excelHeader, CellStyle cellStyle){
    		if(sheet != null && excelHeader != null){
    			Row titleRow = sheet.createRow(0);
    			for(int i = 0;i < excelHeader.length;i++){
    				sheet.setColumnWidth(i, 2000);
    				Cell cell = titleRow.createCell(i, 0);
    				cell.setCellStyle(cellStyle);
    				cell.setCellValue(excelHeader[i]);
    				sheet.setDefaultColumnStyle(i, cellStyle);
    			}
    		}
    	}
    	
    	/** 
    	 * @Title: downloadExcel 
    	 * @Description:    :  workbook   write()      excel       
    	 * @param workbook
    	 * @param outPath
    	 * @return: void
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:08:01
    	 */
    	private static void downloadExcel(Workbook workbook, String outPath){
    		OutputStream os = null;
    		try {
    			os = new FileOutputStream(new File(outPath));
    			workbook.write(os);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    	//           
    	public static void createExcelModel(ExcelModel excelModel, String outPath){
    		if(excelModel != null && outPath != null){
    			Workbook workbook = createWorkbookByType(XLS_TYPE);
    			Sheet sheet = createSheet(workbook, 0, excelModel.getSheetName());
    			CellStyle cellStyle = createCellStyle(workbook);
    			createHeader(sheet, excelModel.getExcelHeader(), cellStyle);
    			downloadExcel(workbook, outPath);
    		}
    	}
    	
    	/**
    	 * 
    	 * @Description:         excel      
    	 */
    	
    	/** 
    	 * @Title: getWorkbook 
    	 * @Description:    :       excel   workbook
    	 * @param is
    	 * @return
    	 * @return: Workbook
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:11:36
    	 */
    	public static Workbook getWorkbook(InputStream is){
    		Workbook workbook = null;
    		if(is != null){
    			try {
    				workbook = WorkbookFactory.create(is);
    			} catch (InvalidFormatException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		return workbook;
    	}
    	
    	/** 
    	 * @Title: getAllData 
    	 * @Description:    : workbook          
    	 * @param path excel       
    	 * @param sheetNo       sheet      
    	 * @return
    	 * @return: List<String[]>
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:12:11
    	 */
    	public static List<String[]> getAllData(String path, int sheetNo){
    		List<String[]> datas = null;
    		Workbook workbook = null;
    		try {
    			workbook = getWorkbook(new FileInputStream(new File(path)));
    			Sheet sheet = workbook.getSheetAt(sheetNo);
    			datas = getAllSheetData(sheet);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}
    		return datas;
    	}
    	
    	private static List<String[]> getAllSheetData(Sheet sheet){
            List<String[]> datas = new ArrayList<String[]>();
    		int columnNum = 0;
    		if(sheet.getRow(0) != null){
    			columnNum = sheet.getRow(0).getLastCellNum() - sheet.getRow(0).getFirstCellNum();
    		}
    		if(columnNum > 0){
    		    for(Row row : sheet){
    		    	String[] singleRow = new String[columnNum];
    		    	for(int i = 0;i < columnNum;i++){
    		    		Cell cell = row.getCell(i, Row.CREATE_NULL_AS_BLANK);
    		    		switch (cell.getCellType()){
    		    		case Cell.CELL_TYPE_BLANK:
                            singleRow[i] = "";
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            singleRow[i] = Boolean.toString(cell.getBooleanCellValue());
                            break;
                        //   
                        case Cell.CELL_TYPE_NUMERIC:
                            if (DateUtil.isCellDateFormatted(cell)) {
                                singleRow[i] = String.valueOf(cell.getDateCellValue());
                            } else {
                                cell.setCellType(Cell.CELL_TYPE_STRING);
                                String temp = cell.getStringCellValue();
                                //          ,       ,       ,      ,    Double      
                                if (temp.indexOf(".") > -1) {
                                    singleRow[i] = String.valueOf(new Double(temp)).trim();
                                } else {
                                    singleRow[i] = temp.trim();
                                }
                            }
                            break;
                        case Cell.CELL_TYPE_STRING:
                            singleRow[i] = cell.getStringCellValue().trim();
                            break;
                        case Cell.CELL_TYPE_ERROR:
                            singleRow[i] = "";
                            break;
                        case Cell.CELL_TYPE_FORMULA:
                            cell.setCellType(Cell.CELL_TYPE_STRING);
                            singleRow[i] = cell.getStringCellValue();
                            if (singleRow[i] != null) {
                                singleRow[i] = singleRow[i].replaceAll("#N/A", "").trim();
                            }
                            break;
                        default:
                            singleRow[i] = "";
                            break;
    		    		}
    		    	}
    		    	datas.add(singleRow);
    		    }
    		}
    		return datas;
    	}
    	
    	public static void main(String[] args) {
    		String[] excelHeader = {"  ","  ","  "};
    		ExcelModel excelModel = new ExcelModel();
    		excelModel.setFileName("    .xls");
    		excelModel.setSheetName("");
    		excelModel.setExcelHeader(excelHeader);
    		createExcelModel(excelModel, "F:/    .xls");
    		System.out.println("          !");
    	}
    }
    

     
    以上の方法で、私たちのニーズに応じて希望するexcelファイルを生成することができますが、多くの場合、excelテンプレートを生成するだけでは十分ではありません.また、インポートしたexcelファイルから対応するデータを解析し、操作可能なオブジェクトを生成する必要があります.そこで、excelからデータを解析する方法について説明します.
     
  • 解析が必要なオブジェクト
  • を生成する.
    package com.excel.util;
    
    public class Student {
    
    	/**
    	 * @Description:     
    	 */
    	private String name;
    	
    	/**
    	 * @Description:     
    	 */
    	private String studentNo;
    	
    	/**
    	 * @Description:     
    	 */
    	private String clazzName;
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getStudentNo() {
    		return studentNo;
    	}
    
    	public void setStudentNo(String studentNo) {
    		this.studentNo = studentNo;
    	}
    
    	public String getClazzName() {
    		return clazzName;
    	}
    
    	public void setClazzName(String clazzName) {
    		this.clazzName = clazzName;
    	}
    	
    }
    

     
     
  • 解析excelデータ
  • package com.excel.util;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class StudentExcelParse {
    
    	static final String[] HEADERS = {"  ","  ","  "};
    	
    	/** 
    	 * @Title: parseExcelModel 
    	 * @Description:   excel        
    	 * @param filePath
    	 * @return
    	 * @return: List<Student>
    	 * @author: zengchao   
    	 * @date: 2015 10 13    3:26:00
    	 */
    	public static List<Student> parseExcelModel(String filePath){
    		List<Student> list = new ArrayList<Student>();
    		List<String[]> datas = ExcelUtil.getAllData(filePath, 0);
    		String[] excelHeaders = datas.get(0);
    		for(int j = 1;j < datas.size();j++){
    			String[] data = datas.get(j);
    			Student student = new Student();
    			if(excelHeaders.length > 0){
    				for(int i = 0;i < excelHeaders.length;i++){
    					if(excelHeaders[i].equals(HEADERS[0])){
    						student.setName(data[i]);
    					} else if(excelHeaders[i].equals(HEADERS[1])){
    						student.setStudentNo(data[i]);
    					} else if(excelHeaders[i].equals(HEADERS[2])){
    						student.setClazzName(data[i]);
    					}
    				}
    			}
    			list.add(student);
    		}
    		return list;
    	}
    	
    	public static void main(String[] args) {
    		List<Student> list =parseExcelModel("F:/    .xls");
    		for(Student stu : list){
    			System.out.println(stu.getName() + "--->" + stu.getStudentNo());
    		}
    	}
    }
    

     
    以上がexcelの完全な操作の流れで、今回の文章は個人の総括学習に用いて、もし適切でない地方があればみんなに含んでください!