java使用poi讀取excel

首先需要公共類ExcelUtil



import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil {
    //默認單元格內容爲數字時格式
    private static DecimalFormat df = new DecimalFormat("0");
    // 默認單元格格式化日期字符串 
//  private static SimpleDateFormat sdf = new SimpleDateFormat(  "yyyy-MM-dd HH:mm:ss"); 
    // 格式化數字
    private static DecimalFormat nf = new DecimalFormat("0");  
    public static ArrayList<ArrayList<Object>> readExcel(File file){
        if(file == null){
            return null;
        }
        if(file.getName().endsWith("xlsx")){
            //處理ecxel2007
            return readExcel2007(file);
        }else{
            //處理ecxel2003
            return readExcel2003(file);
        }
    }
    /*
     * @return 將返回結果存儲在ArrayList內,存儲結構與二位數組類似
     * lists.get(0).get(0)表示過去Excel中0行0列單元格
     */
    public static ArrayList<ArrayList<Object>> readExcel2003(File file){
        try{
            ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
            ArrayList<Object> colList;
            HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(file));
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row;
            HSSFCell cell;
            Object value;
            for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
                row = sheet.getRow(i);
                colList = new ArrayList<Object>();
                if(row == null){
                    //當讀取行爲空時
                    if(i != sheet.getPhysicalNumberOfRows()){//判斷是否是最後一行
                        rowList.add(colList);
                    }
                    continue;
                }else{
                    rowCount++;
                }
                for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
                    cell = row.getCell(j);
                    if(cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
                        //當該單元格爲空
                        if(j != row.getLastCellNum()){//判斷是否是該行中最後一個單元格
                            colList.add("");
                        }
                        continue;
                    }
                    switch(cell.getCellType()){
                     case XSSFCell.CELL_TYPE_STRING:  
                           // System.out.println(i + "行" + j + " 列 is String type");  
                            value = cell.getStringCellValue();  
                            break;  
                        case XSSFCell.CELL_TYPE_NUMERIC:  
                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {  
                                value = df.format(cell.getNumericCellValue());  
                            } else {  
                                value = nf.format(cell.getNumericCellValue());  
                            }   
                          //  System.out.println(i + "行" + j  
                            //        + " 列 is Number type ; DateFormt:"  
                            //        + value.toString()); 
                            break;  
                        case XSSFCell.CELL_TYPE_BOOLEAN:  
                         //   System.out.println(i + "行" + j + " 列 is Boolean type");  
                            value = Boolean.valueOf(cell.getBooleanCellValue());
                            break;  
                        case XSSFCell.CELL_TYPE_BLANK:  
                         //   System.out.println(i + "行" + j + " 列 is Blank type");  
                            value = "";  
                            break;  
                        default:  
                      //      System.out.println(i + "行" + j + " 列 is default type");  
                            value = cell.toString();  
                    }// end switch
                    colList.add(value);
                }//end for j
                rowList.add(colList);
            }//end for i

            return rowList;
        }catch(Exception e){
            return null;
        }
    }

    public static ArrayList<ArrayList<Object>> readExcel2007(File file){
        try{
            ArrayList<ArrayList<Object>> rowList = new ArrayList<ArrayList<Object>>();
            ArrayList<Object> colList;
            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(file));
            //第一面是0
            //XSSFSheet sheet = wb.getSheetAt(0);
            XSSFSheet sheet = wb.getSheetAt(0);

            XSSFRow row;
            XSSFCell cell;
            Object value;
            for(int i = sheet.getFirstRowNum() , rowCount = 0; rowCount < sheet.getPhysicalNumberOfRows() ; i++ ){
                row = sheet.getRow(i);
                colList = new ArrayList<Object>();
                if(row == null){
                    //當讀取行爲空時
                    if(i != sheet.getPhysicalNumberOfRows()){//判斷是否是最後一行
                        rowList.add(colList);
                    }
                    continue;
                }else{
                    rowCount++;
                }
                for( int j = row.getFirstCellNum() ; j <= row.getLastCellNum() ;j++){
                    cell = row.getCell(j);
                    if(cell == null || cell.getCellType() == HSSFCell.CELL_TYPE_BLANK){
                        //當該單元格爲空
                        if(j != row.getLastCellNum()){//判斷是否是該行中最後一個單元格
                            colList.add("");
                        }
                        continue;
                    }
                    switch(cell.getCellType()){
                     case XSSFCell.CELL_TYPE_STRING:  
                         //   System.out.println(i + "行" + j + " 列 is String type");  
                            value = cell.getStringCellValue();  
                            break;  
                        case XSSFCell.CELL_TYPE_NUMERIC:  
                            if ("@".equals(cell.getCellStyle().getDataFormatString())) {  
                                value = df.format(cell.getNumericCellValue());  
                            } else {  
                                value = nf.format(cell.getNumericCellValue());  
                            } 
                       //     System.out.println(i + "行" + j  
                               //     + " 列 is Number type ; DateFormt:"  
                              //      + value.toString()); 
                            break;  
                        case XSSFCell.CELL_TYPE_BOOLEAN:  
                         //   System.out.println(i + "行" + j + " 列 is Boolean type");  
                            value = Boolean.valueOf(cell.getBooleanCellValue());
                            break;  
                        case XSSFCell.CELL_TYPE_BLANK:  
                          //  System.out.println(i + "行" + j + " 列 is Blank type");  
                            value = "";  
                            break;  
                        default:  
                           // System.out.println(i + "行" + j + " 列 is default type");  
                            value = cell.toString();  
                    }// end switch
                    colList.add(value);
                }//end for j
                rowList.add(colList);
            }//end for i

            return rowList;
        }catch(Exception e){
            //System.out.println("exception");
            return null;
        }
    }

    public static void writeExcel(ArrayList<ArrayList<Object>> result,String path){
        if(result == null){
            return;
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("sheet1");
        for(int i = 0 ;i < result.size() ; i++){
             HSSFRow row = sheet.createRow(i);
            if(result.get(i) != null){
                for(int j = 0; j < result.get(i).size() ; j ++){
                    HSSFCell cell = row.createCell(j);
                    cell.setCellValue(result.get(i).get(j).toString());
                }
            }
        }
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try
        {
            wb.write(os);
        } catch (IOException e){
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        File file = new File(path);//Excel文件生成後存儲的位置。
        OutputStream fos  = null;
        try
        {
            fos = new FileOutputStream(file);
            fos.write(content);
            os.close();
            fos.close();
        }catch (Exception e){
            e.printStackTrace();
        }           
    }

    public static DecimalFormat getDf() {
        return df;
    }
    public static void setDf(DecimalFormat df) {
        ExcelUtil.df = df;
    }
    public static DecimalFormat getNf() {
        return nf;
    }
    public static void setNf(DecimalFormat nf) {
        ExcelUtil.nf = nf;
    }



}

main測試

import java.io.File;
import java.util.ArrayList;

import util.ExcelUtil;

/**
 * 類說明
 * 
 * @author nmj
 * @email [email protected]
 * @date 2017年5月17日 新建
 */
public class dq {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            File file = new File("C:\\Users\\nmj\\Desktop\\test.xls");
            ExcelUtil eu = new ExcelUtil();
            // 從行至列
            ArrayList<ArrayList<Object>> list = eu.readExcel(file);
            int ia = 0;
            // 讀出行
            for (int i = 0; i < list.size(); i++) {
                ArrayList<Object> list_hang = list.get(i);
                for (int j = 0; j < list_hang.size(); j++) {
                    System.out.println("第" + i + "行第" + j + "列爲【"
                            + list.get(i).get(j) + "】");
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

}

相關jar下載:http://download.csdn.net/download/nmj2015/9844443

發佈了37 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章