EXCEL,POI,EASYEXCEL的使用和比較

qq_33867986發表於2020-11-18

記錄一次處理Excel


需求是將八個Excel資料合併到一個Excel表當中,這八個Excel資料的表格式相同,所以其實對於資料的讀取是一樣的。

EasyExcel

easyexcel是阿里巴巴開源的一個處理excel的工具包,同時因為easyescel有中文文件,而且操作簡單,所以一開始使用了easyexcel,但是在使用過程中發現,它所提供的api不夠全面,無法做到精確定位,精確操作,只能一列一列來讀寫,而且無法在過程中進行判斷什麼的。
總的來說,不夠靈活,但足夠簡單。

POI

poi是apache的一個子專案,專門用來處理Excel的,不管怎麼說,這個幫大忙了,雖然操作相對於easyexcel來說複雜一點,但是也挺簡單的,基本上一小時上手,三小時會用,用一天就已經算比較熟悉了。

處理思路

一開始,我計劃用easyexcel全部處理完成,但是不夠靈活。
然後我盯上了poi,稍微學了下,一開始想著先把要讀的檔案讀出來到map<name, content>中,然後在把要寫的檔案讀出來它的<name, index>,然後再根據座標和內容的匹配寫進去,但是!一直報空指標錯誤,怎麼樣搞都不行。
但是最後我換了中方法解決了。用的是在用outputstream的同時獲取excel的資訊來做判斷,程式碼如下:

public class RunToThat {
    public void sonofbitch() throws Exception{
        List<String> list = new ArrayList<>();
        list.add("0");list.add("0_left");list.add("1_left");list.add("2");list.add("2_left");list.add("3");list.add("3_left");list.add("1");
        for(String a : list){
            ojbk(a);
        }
    }
    public void ojbk(String a) throws Exception{
        readListener readListener = new readListener();

        String Readfilename = "C:\\Users\\12979\\Desktop\\ok\\"+a+".xlsx";
        System.out.println("讀取中!");
        EasyExcel.read(Readfilename, DemoData.class,readListener).sheet().doRead();


        FileInputStream fileInputStream=new FileInputStream("C:\\Users\\12979\\Desktop\\ok\\last.xlsx");  //獲取d://test.xls,建立資料的輸入通道
        System.out.println(fileInputStream);
        //POIFSFileSystem poifsFileSystem=new POIFSFileSystem(fileInputStream);  //使用POI提供的方法得到excel的資訊
        System.out.println("excel-1的資訊:"+fileInputStream);
        XSSFWorkbook Workbook= new XSSFWorkbook(fileInputStream);//得到文件物件
        System.out.println("excel-2的資訊:"+Workbook);
        XSSFSheet sheet=Workbook.getSheet("sheet1");  //根據name獲取sheet表
        System.out.println("excel-3的資訊:"+sheet);
        Map<String,String> map = readListener.map;
        System.out.println(map);
        for(int i  = 1; i < sheet.getLastRowNum(); i++){
            String fuck = sheet.getRow(i).getCell(0).toString();
            String ok;
            if(fuck.length() >= 3){
                ok = fuck.substring(0,3);
            }else {
                ok = fuck;
            }
            System.out.println(ok);
            if(map.get(ok)!= null){
                System.out.println("aha"+sheet.getRow(i).getCell(0));
                XSSFRow row=sheet.getRow(i);  //獲取第一行

                FileOutputStream out=new FileOutputStream("C:\\Users\\12979\\Desktop\\ok\\last.xlsx");  //向d://test.xls中寫資料
                XSSFCell cell = row.createCell(5);

                cell.setCellValue(map.get(ok));
                out.flush();
                Workbook.write(out);
                out.close();
            }
        }

    }
}

好了,結束!

相關文章