Java實現對Excel文件的讀取、操作


1.項目所需jar包,poi-3.9-20121203.jar,poi-ooxml-3.9.jar,poi-ooxml-schemas-3.9.jar

2.案例參考

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.xssf.usermodel.XSSFWorkbook;

import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

public class Excel01 {

    public static void main(String[] args) throws IOException,ParseException{
        System.out.println(">>>>>>>>>>>>>讀取Excel");
        Workbook wb = null; 
        Sheet sheet = null;
        Row row = null;
        List<Map<String,String>> list = null;
        String cellData = null;
        String filePath = "D:\\Zexcel\\E.xlsx";
        String columns[] = {"a","b","c","d"};
        wb=readExcel(filePath);
        if (wb != null) {
            //用來存放表中數據
            list = new ArrayList<Map<String,String>>();
            //獲取第一個sheet
            sheet = wb.getSheetAt(0);
            //獲取最大行數
            int rownum = sheet.getPhysicalNumberOfRows();
            System.out.println("最大行數"+rownum);
            //獲取第一行
            row = sheet.getRow(1);
            //獲取最大列數
            int colnum = row.getPhysicalNumberOfCells();
            System.out.println("最大列數"+colnum);
            for (int i = 1; i < rownum; i++) {
                Map<String,String> map = new LinkedHashMap<String,String>();
                row = sheet.getRow(i);
                if (row!=null) {
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String)getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                } else {
                    break;
                }
                list.add(map);
            }
        }
        //遍歷解析出來的list
        FileWriter idAndPolict = new FileWriter("D:\\Zexcel\\n.txt");
        String temp = ",";
        String tempEnd = " from A;";
        //select a,b,c,d from A;
        for (Map<String,String> map : list) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("select ").append(map.get("a")).append(temp).append(map.get("b")).append(temp).append(map.get("c")).append(temp).append(map.get("d")).append(tempEnd);
            //寫入ds文件
            idAndPolict.write(stringBuffer.toString().toString()+"\r\n");
            idAndPolict.flush();
        }
    }

    //讀取Excel
    public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if (filePath==null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
    
    //Excel值轉化
    public static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        if (cell!=null) {
            //判斷cell類型
            switch(cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC:{
                if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
                    Date theDate = cell.getDateCellValue();
                    SimpleDateFormat dff = new SimpleDateFormat("yyyy/MM/dd");
                    cellValue = dff.format(theDate);
                } else {
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue());
                }
                break;
            }
            case Cell.CELL_TYPE_FORMULA:{
                //判斷cell是否為日期格式
                if (DateUtil.isCellDateFormatted(cell)) {
                    //轉換為日期格式yyyy-mm-dd
                    cellValue = cell.getDateCellValue();
                } else {
                    //數字
                    cellValue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            }
            case Cell.CELL_TYPE_STRING:{
                cellValue = cell.getRichStringCellValue().getString();
                break;
            }
            default:
                cellValue = "";
            }
            
        }else{
            cellValue = "";
        }
        return cellValue;
        
    }
    
    
}

 


免責聲明!

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



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