将excel表导入数据库

public class ExcelToData {

    public static void excel2Data(Connection conn, String excelPath) throws FileNotFoundException {
        try {
            excelPath = "C:\\Users\\Administrator\\Desktop\\test.xlsx";
            //String encoding = "GBK";
            File excel = new File(excelPath);
            if (excel.isFile() && excel.exists()) {   //判断文件是否存在

                String[] split = excel.getName().split("\\.");  //.是特殊字符,需要转义!!!!!
                Workbook wb = null;
                //根据文件后缀(xls/xlsx)进行判断
                if ("xls".equals(split[1])) {
                    InputStream fis = new FileInputStream(excel);   //文件流对象
                    wb = new HSSFWorkbook(fis);
                } else if ("xlsx".equals(split[1])) {
                    InputStream fis = new FileInputStream(excel);
                    wb = new XSSFWorkbook(fis);
                } else {
                    System.out.println("文件类型错误!");
                    return;
                }
                //开始解析
                Sheet sheet = wb.getSheetAt(0);     //读取sheet 0
                int firstRowIndex = sheet.getFirstRowNum() + 2;   //第一行是列名,所以不读
                int lastRowIndex = sheet.getLastRowNum();
                String name = null;
                String age = null;
                String sex = null;
                //属性字段行
                Row title = sheet.getRow(firstRowIndex - 1);
                for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                    Row row = sheet.getRow(rIndex);
                    if (row != null) {
                        int firstCellIndex = title.getFirstCellNum();
                        int lastCellIndex = title.getLastCellNum();
                        for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
                            Cell cell = row.getCell(cIndex);
                            if (cell != null && !"".equals(cell.toString().trim())) {
                                switch (cIndex) {
                                    case 0:
                                        name = cell.toString();
                                        break;
                                    case 1:
                                        age = cell.toString();
                                        break;
                                    case 2:
                                        sex = cell.toString();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        insertMethod(conn, name, age, sex);
                    }
                }
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void insertMethod(Connection conn, String name, String age, String sex) {
        try {
            //excel表中的数字会转换为字符串,如11会变成'11.0',需要手动将其转回成数字
            int i = age.lastIndexOf(".");
            String substring = age.substring(0, i);
            Integer age1 = Integer.valueOf(substring);
            String sql = "insert into test(name,age,sex) values(?,?,?)";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, name);
            statement.setInt(2, age1);
            statement.setString(3, sex);
            statement.executeUpdate();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}

以上代码合并单元格也可使用,但是在单元格出现空值时,会默认为上一行相同位置单元格内容

以下是我项目中的源码,但是合并单元格会报错,空单元格也会报错,必须每格都填

/**
     * Description : 将excel导入数据库
     *
     * @param inputStream
     * @param extName  文件后缀
     * @param fileId
     * @return : void
     * @throws Exception
     * @date : 2019-01-23   09:18
     * @author : PZG
     */
    public void excel2Data(InputStream inputStream, String extName, Integer fileId) throws CustomException {
        try {
            Workbook wb = null;
            //根据文件后缀(xls/xlsx)进行判断
            if ("xls".equals(extName)) {
                wb = new HSSFWorkbook(inputStream);
            } else if ("xlsx".equals(extName)) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                throw new CustomException("上传文件不是excel文件!");
            }
            //开始解析
            Sheet sheet = wb.getSheetAt(0);     //读取sheet 0
            int firstRowIndex = sheet.getFirstRowNum() + 2;   //第一行是列名,所以不读
            int lastRowIndex = sheet.getLastRowNum();
            List<ProcessExcelInfo> processExcelInfoList = new ArrayList<>();
            String ProvideOgName = null;
            String ProvideOgCode = null;
            String ApplyDataName = null;
            String ApplyDataInfo = null;
            String DataType = null;
            String ApplyReason = null;

            //属性字段行
            Row title = sheet.getRow(firstRowIndex - 1);

            for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {   //遍历行
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    ProcessExcelInfo processExcelInfo = new ProcessExcelInfo();
                    int firstCellIndex = title.getFirstCellNum();
                    int lastCellIndex = title.getLastCellNum();
                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {   //遍历列
                        Cell cell = row.getCell(cIndex);

                        //获取空值的单元格
                        if (cell == null || "".equals(cell.toString().trim())) {
                            Integer rr = (rIndex + 1);
                            Integer cc = (cIndex + 1);
                            String ss = (char) (cc + 64) + "";
                            String asd = ss + rr;
                            throw new CustomException("excel文件导入数据库失败:"+asd + " 单元格空值!");
                        } else {
                            switch (cIndex) {
                                case 0:
                                    ProvideOgName = cell.toString();
                                    break;
                                case 1:
                                    ProvideOgCode = cell.toString();
                                    break;
                                case 2:
                                    ApplyDataName = cell.toString();
                                    break;
                                case 3:
                                    ApplyDataInfo = cell.toString();
                                    break;
                                case 4:
                                    DataType = cell.toString();
                                    break;
                                case 5:
                                    ApplyReason = cell.toString();
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    processExcelInfo.setProvideOgName(ProvideOgName);
                    processExcelInfo.setProvideOgCode(ProvideOgCode);
                    processExcelInfo.setApplyDataName(ApplyDataName);
                    processExcelInfo.setApplyDataInfo(ApplyDataInfo);
                    processExcelInfo.setDataType(DataType);
                    processExcelInfo.setDataType(DataType);
                    processExcelInfo.setApplyReason(ApplyReason);
                    processExcelInfo.setFileId(fileId);
                    processExcelInfo.setMeetingResult(4);
                    processExcelInfoList.add(processExcelInfo);
                }
            }
            insertMethod(processExcelInfoList);
        }catch (CustomException e){
            throw e;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("excel文件导入数据库失败");
        }
    }

    /**
     * Description : 向表中插入数据
     *
     * @param processExcelInfoList
     * @return : void
     * @throws Exception
     * @date : 2019-01-23   09:19
     * @author : PZG
     */
    public void insertMethod(List<ProcessExcelInfo> processExcelInfoList) {
        processExcelInfoMapper.insertList(processExcelInfoList);
    }

猜你喜欢

转载自blog.csdn.net/qq_41991665/article/details/86598011