Apache POI -- 读取Excel文件数据导入到数据库

前言:使用Apache 旗下 POI读取Excel文件中的数据插入到数据库。

一、导jar包
① poi
② poi-ooxml
③ poi-ooxml-schemas
④ dom4j
⑤ xmlbeans

二、解决03和07版本不同API问题

1、判断文件后缀.xls或者.xlsx,来使用HSSFWorkbook(03)还是XSSFWorkbook(07)API。

2、因为判断文件后缀麻烦,可以直接通过异常来实现。灵感来源博客:博客地址。以下使用方法思路相同但稍作修改。

三、Java代码实现
1、ExcelFileReadUtil实现

public class ExcelFileReadUtil {

    /**
     * 读取Excel文件方法
     * @param upload //上传文件File对象
     * @return Sheet
     */
    public static Sheet readExcelFile03Or07(File upload) {
        Workbook workbook = null;
        Sheet sheet = null;
        try {

            //默认使用03版本API读取Excel文件
            //如果文件在本地,也可以传入new FileInputStream(new File(pathname))
            workbook = new HSSFWorkbook(new FileInputStream(upload));
            sheet = workbook.getSheetAt(0);
            return sheet;


        } catch (OfficeXmlFileException e) {//这里捕获的异常不是Exception,换成OfficeXmlFileException
            try {


                //如何出现此异常则使用07API读取Excel文件
                workbook = new XSSFWorkbook(new FileInputStream(upload));
                sheet = workbook.getSheetAt(0);
                return sheet;

            } catch (FileNotFoundException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }finally {

                try {

                    //关闭资源
                    workbook.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {

                //关闭资源
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sheet;
    }
}

2、为什么将catch 的 Exception 替换成OfficeXmlFileException
① 在源码的注释当中我们可以看到,使用03API读07文件时抛出此异常。但是并不能确定不会出现其他异常,所有Exception范围太大。

②源码

/* ====================================================================
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
==================================================================== */

package org.apache.poi.poifs.filesystem;

/**
 * This exception is thrown when we try to open a file that's actually
 *  an Office 2007+ XML file, rather than an OLE2 file (which is what
 *  POIFS works with)
 */
public class OfficeXmlFileException extends IllegalArgumentException {
    public OfficeXmlFileException(String s) {
        super(s);
    }
}

3、读取数据

//调用ExcelFileRead工具类读取Excel文件
        Sheet sheet = ExcelFileReadUtil.readExcelFile03Or07(upload);
        List<Area> areas = new ArrayList<>();
        Area area;

        //循环遍历行
        for (Row row : sheet) {

            //跳过表头
            if (row.getRowNum() == 0) {

                continue;
            }

            //获取每行单个元素值
            String id = row.getCell(0).getStringCellValue();
            String province = row.getCell(1).getStringCellValue();
            String city = row.getCell(2).getStringCellValue();
            String district = row.getCell(3).getStringCellValue();
            String postcode = row.getCell(4).getStringCellValue();

            //封装数据
            area = new Area(id, province, city, district, postcode,null, null);
            areas.add(area);
        }

猜你喜欢

转载自blog.csdn.net/m0_37602117/article/details/79768198