Java集成POI進行Excele的導入導出,以及報錯: java.lang.AbstractMethodError..........


報錯信息如下

 java.lang.AbstractMethodError: org.apache.poi.xssf.usermodel.XSSFCell.setCellType(Lorg/apache/poi/ss/usermodel/CellType;

 

 

首先項目集成POI進行導入導出的pom文件

注意:最開始我使用的是3.15和3.14,但是會產生上面的報錯信息,我這邊一直以為是我代碼存在問題, 反復修改之后還是存在問題,最后翻牆查了下stackoverflow,感覺出錯的原因是poi的版本過低,於是將這邊都修改成下面的4.0.0,最后解決問題

https://stackoverflow.com/questions/39993683/alternative-to-deprecated-getcelltype

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>

准備工作,將本地文件夾中的excel,准備好,修改demo中的地址

寫入Excele的demo

package com.excel.demo.util;

import com.excel.demo.model.User;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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 java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class WriteExcel {
    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";

    public static void main(String[] args) {
//        ArrayList<String> strings = new ArrayList<>();
//        strings.add("1");
//        strings.add("2");
//        strings.add("3");
//        strings.add("4");
//        strings.add("5");
//        strings.add("6");
//        strings.add("7");
//        writeExcelToRow(strings, 3, "E:/writeExcel.xlsx");

        ArrayList<User> vos = new ArrayList<>();
        User user = new User();
        user.setAddress("地球村");
        user.setLove("喜洋ccccc洋");
        user.setAge(18);
        user.setName("張三");
        user.setSex(true);
        vos.add(user);
        vos.add(user);
        vos.add(user);
        vos.add(user);
        writeExcelVo(vos, "E:/writeExcel.xlsx");

    }

    //向Excel里存儲對象
    public static void writeExcelVo(List<User> dataList, String finalXlsxPath) {
        OutputStream out = null;
        try {
            // 獲取總列數
            int columnNumCount = dataList.size();
            // 讀取Excel文檔
            File finalXlsxFile = new File(finalXlsxPath);
            Workbook workBook = getWorkbok(finalXlsxFile);
            // sheet 對應一個工作頁
            Sheet sheet = workBook.getSheetAt(0);
            /**
             * 刪除原有數據,除了屬性列
             */
            int rowNumber = sheet.getLastRowNum();    // 第一行從0開始算
            System.out.println("原始數據總行數,除屬性列:" + rowNumber);
            for (int i = 1; i <= rowNumber; i++) {
                Row row = sheet.getRow(i);
                if(row==null){
                    continue;
                }
                sheet.removeRow(row);
            }
            // 創建文件輸出流,輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
            /**
             * 往Excel中寫新數據
             */
            for (int j = 0; j < dataList.size(); j++) {

                // 創建一行:從第二行開始,跳過屬性列
                Row row = sheet.createRow(j + 1);
                // 得到要插入的每一條記錄
                //TODO 下面可以進行優化,使用反射獲取字段數量,然后對字段進行遍歷,在存儲,這樣可以減少手寫代碼的量
                User user = dataList.get(j);

                // 在一行內循環
                Cell first = row.createCell(0);
                first.setCellValue(user.getName());

                Cell second = row.createCell(1);
                second.setCellValue(user.getAge());

                Cell third = row.createCell(2);
                third.setCellValue(user.getLove());

                Cell c4 = row.createCell(4);
                c4.setCellValue(user.getAddress());

                Cell c5 = row.createCell(5);
                c5.setCellValue(user.isSex());
            }
            // 創建文件輸出流,准備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("數據導出成功");
    }

    public static void writeExcel(List<Map> dataList, int cloumnCount, String finalXlsxPath) {
        OutputStream out = null;
        try {
            // 獲取總列數
            int columnNumCount = cloumnCount;
            // 讀取Excel文檔
            File finalXlsxFile = new File(finalXlsxPath);
            Workbook workBook = getWorkbok(finalXlsxFile);
            // sheet 對應一個工作頁
            Sheet sheet = workBook.getSheetAt(0);
            /**
             * 刪除原有數據,除了屬性列
             */
            int rowNumber = sheet.getLastRowNum();    // 第一行從0開始算
            System.out.println("原始數據總行數,除屬性列:" + rowNumber);
            for (int i = 1; i <= rowNumber; i++) {
                Row row = sheet.getRow(i);
                if(row==null){
                    continue;
                }
                sheet.removeRow(row);
            }
            // 創建文件輸出流,輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
            /**
             * 往Excel中寫新數據
             */
            for (int j = 0; j < dataList.size(); j++) {
                // 創建一行:從第二行開始,跳過屬性列
                Row row = sheet.createRow(j + 1);
                // 得到要插入的每一條記錄
                Map dataMap = dataList.get(j);
                String name = dataMap.get("BankName").toString();
                String address = dataMap.get("Addr").toString();
                String phone = dataMap.get("Phone").toString();
                for (int k = 0; k <= columnNumCount; k++) {
                    // 在一行內循環
                    Cell first = row.createCell(0);
                    first.setCellValue(name);

                    Cell second = row.createCell(1);
                    second.setCellValue(address);

                    Cell third = row.createCell(2);
                    third.setCellValue(phone);
                }
            }
            // 創建文件輸出流,准備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("數據導出成功");
    }

    /**
     * 指定行里面添加數據
     *
     * @param dataList
     * @param rowNum
     * @param finalXlsxPath
     */
    public static void writeExcelToRow(List<String> dataList, int rowNum, String finalXlsxPath) {
        OutputStream out = null;
        try {
            // 獲取總列數
            int columnNumCount = rowNum;
            // 讀取Excel文檔
            File finalXlsxFile = new File(finalXlsxPath);
            Workbook workBook = getWorkbok(finalXlsxFile);
            // sheet 對應一個工作頁
            Sheet sheet = workBook.getSheetAt(0);
            /**
             * 刪除原有數據,除了屬性列
             */
            int rowNumber = sheet.getLastRowNum();    // 第一行從0開始算
            System.out.println("原始數據總行數,除屬性列:" + rowNumber);
            for (int i = 1; i <= rowNumber; i++) {
                Row row = sheet.getRow(i);
                if(row==null){
                    continue;
                }
                sheet.removeRow(row);
            }
            // 創建文件輸出流,輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
            /**
             * 往Excel中寫新數據
             */
            Row row = sheet.createRow(columnNumCount);
            for (int j = 0; j < dataList.size(); j++) {
                // 創建一行:從第二行開始,跳過屬性列
                // 得到要插入的每一條記錄
                row.createCell(j).setCellValue(dataList.get(j));

            }
            // 創建文件輸出流,准備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
            out = new FileOutputStream(finalXlsxPath);
            workBook.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("數據導出成功");
    }

    /**
     * 判斷Excel的版本,獲取Workbook
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException {
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if (file.getName().endsWith(EXCEL_XLS)) {     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        } else if (file.getName().endsWith(EXCEL_XLSX)) {    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }
}

 

讀取Excel的demo

package com.excel.demo.util;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ReadExcel {
    private static final String EXCEL_XLS = "xls";
    private static final String EXCEL_XLSX = "xlsx";


    public static void main(String[] args) {
        ReadExcel obj = new ReadExcel();
        File file = new File("E:/readExcel1.xls");
        List excelList = obj.readExcel(file);
        System.out.println("list中的數據打印出來");
        for (int i = 0; i < excelList.size(); i++) {
            List list = (List) excelList.get(i);
            for (int j = 0; j < list.size(); j++) {
                System.out.print(list.get(j));
            }
            System.out.println();
        }

    }


    // 去讀Excel的方法readExcel,該方法的入口參數為一個File對象
    public List readExcel(File file) {
        try {
            // 創建輸入流,讀取Excel
            Workbook wb = getWorkbok(file);
            // Excel的頁簽數量
            int sheetSize = wb.getNumberOfSheets();
            for (int index = 0; index < sheetSize; index++) {
                List<List> outerList = new ArrayList<List>();
                // 每個頁簽創建一個Sheet對象
                Sheet sheet = wb.getSheetAt(index);
                // sheet.getLastRowNum()返回該頁的總行數
                for (int i = 0; i < sheet.getLastRowNum(); i++) {
                    List innerList = new ArrayList();
                    // row.getPhysicalNumberOfCells()返回該頁的總列數
                    Row row = sheet.getRow(i);
                    for (int j = 0; j < row.getPhysicalNumberOfCells(); j++) {
                        Cell cell = row.getCell(j);
                        String value = getCellValue(cell);
                        if (value.isEmpty()) {
                            continue;
                        }
                        innerList.add(value);
                        System.out.print(value + "\t");
                    }
                    outerList.add(i, innerList);
                    System.out.println();
                }
                return outerList;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 判斷Excel的版本,獲取Workbook
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static org.apache.poi.ss.usermodel.Workbook getWorkbok(File file) throws IOException {
        org.apache.poi.ss.usermodel.Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if (file.getName().endsWith(EXCEL_XLS)) {     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        } else if (file.getName().endsWith(EXCEL_XLSX)) {    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

   
    private static String getValue(Cell cell) {
        String value = null;
        switch (cell.getCellType()) {
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    Date date = cell.getDateCellValue();
                    DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
                    value = formater.format(date);
                } else if (String.valueOf(cell.getNumericCellValue()).contains(".")) {
                    DecimalFormat df = new DecimalFormat("#");
                    value = df.format(cell.getNumericCellValue());
                } else {
//                    value = (cell + "").trim();
                    value = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case STRING:
                value = cell.getStringCellValue();
                break;
            case FORMULA:
                break;
            case BLANK:
                value = "";
                break;
            case BOOLEAN:
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case ERROR:
                break;
            default:
                break;
        }

        return value;
    }


     /**
     * 不同類型對應不同的取值范圍
     *
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell) {
        String value = "";
        switch (cell.getCellType()) {
            case STRING:
                value = cell.getRichStringCellValue().getString();
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    value = cell.getDateCellValue().toString();
                } else {
                    value = String.valueOf(cell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                value = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                value = cell.getCellFormula();
                break;
            case BLANK:
                break;
            default:
        }
        return value;
    }



}

 

上面兩個Demo,第一個基本上摘自別人博客的,但是第二個,別人博客是試用jxl進行讀取的,所以這邊將讀取的邏輯改成了新版的POI對Excel進行讀取,新的讀取主要是增加了getCellTypeEnum()來判斷單元格數據類型,最后在根據枚舉類型返回需要的結果,之前的方法是cell.getCellTypeEnum()我這邊看了下代碼是一個已經被廢棄的,所以就使用getCellTypeEnum()來進行取代了.

 

運行結果如下


免責聲明!

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



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