POI using the data parsing in Excel

Preface:

March winds do not blow away the haze, then let it April sun on earth, forget the past, look to the future. Goodbye March, April hello.

In recent POI use to import data from Excel to the database, then I will explain how to use the POI.

concept:

Apache POI is the Apache Software Foundation's open-source libraries, POI provides an API to the Java program to read and write Microsoft Office file format functions.

step:

  • (1) introduced in pom.xml jar package.
  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
  • (2) the front page.

    <template>
    <div class="root">
     
            <el-upload class="zh-upload"  :before-upload="beforeExportExcel" :show-file-list=false  :action="UploadUrl()" :on-success="exportExcel" :file-list="fileList">
                <el-button type="primary" size="mini"  >导入模板</el-button>
            </el-upload>
    </div>
</template>

<script>
  export default {
      name: "Register",
      data() {
          return {
              fileList:[],
              Register: {
                  phone: '',
                  sendcode: '',
              },
              disabled: false,
              time: 0,
              btntxt: "重新发送",
              timeToggle:false,
              dataTable:{
                pid:"11",
                mie:'dasdasdasd'
              }
          }
      },
      created() {
        const {pid} = this.dataTable
        console.log(pid)
      },
      methods: {
        //导入
        importClick() {

        },
        UploadUrl () {
          return '/api/readExcelData'
        },
        // 导出
        beforeExportExcel(file) {
          console.log(file)
            const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';

            if (!isXLSX) {
                this.$message.error('上传模板只能是 XLSX 格式!');
            }
            return isXLSX ;
        },
        exportExcel (file, fileList) {

          if (file.result="true") {
              this.$message({
                  message: file.message,
                  type: 'success'
              });
          }else {
              this.$message({
                  message: file.message,
                  type: 'error'
              });
          }
        },
      }
  }
</script>




 

  • (3) back-end interface. 

  Interface: readExcelData

  /**
     * 导入excel
     *
     * @param
     * @return
     */
    @PostMapping(value = "/readExcelData")
    public ResultData readExcel(MultipartFile file, HttpSession session) {
        ResultData result = new ResultData();
        if (!file.isEmpty()) {
            try {
                //取得文件原名
                String filename = file.getOriginalFilename();
                //取得文件后缀名
                Integer indexStar = filename.lastIndexOf(".") + 1;
                //取得文件后缀名
                String excelTypeName = filename.substring(indexStar);
                //当前登录用户
                BosUserModel userModel = (BosUserModel) session.getAttribute("user");
                //解析Excel中的数据
                result = poiExcelService.readExcelToCustomer(file.getInputStream(), excelTypeName, userModel.getName());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

 

  • (4) PoiExcelService class information:
 public static final String EXCEL_TYPE_2007 = "xlsx";
/**
     * 读取Excel中的数据到客户表中
     * @param inputStream
     * @param excelTypeName
     * @param name
     */
    @Override
    public ResultData readExcelToCustomer(InputStream inputStream, String excelTypeName, String name) {
        ResultData resultData = new ResultData();
        Workbook wb = null;
        try {
            if (EXCEL_TYPE_2007.equals(excelTypeName)) {
                wb = new XSSFWorkbook(inputStream);
            } else {
                wb = new HSSFWorkbook(inputStream);
            }
            //获得excel中第一个表格
            Sheet sheet = wb.getSheetAt(0);
            boolean flag = true;
            for (Row cells : sheet) {
                //跳过第一行
                if (flag == true) {
                    flag = false;
                    continue;
                }

                System.out.println("第1个字段:----"+toStringValue(cells.getCell(0)));
                System.out.println("第2个字段:----"+toStringValue(cells.getCell(1)));
                System.out.println("第3个字段:----"+toStringValue(cells.getCell(2)));
                System.out.println("第4个字段:----"+toStringValue(cells.getCell(3)));
                System.out.println("第5个字段:----"+toStringValue(cells.getCell(4)));
                System.out.println("第6个字段:----"+toStringValue(cells.getCell(5)));

            }
            resultData.setResult("true");
            resultData.setMessage("导入客户数据成功");
        } catch (Exception e) {
            resultData.setResult("false");
            resultData.setMessage("导入客户数据失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("导入数据到商机表单中失败",e);
        }
        return resultData;
    }

In fact, I read the article data in Excel, when there is a problem that toStringValue () I will read the values are all converted into String, Excel, if there is a line type of field is the value of time, parsing out data is a problem. I used the following methods no problem. I refer to is this article

 public static String getCellStringValue(Cell cell) {
        String cellValue = "";
        if (cell != null) {
            // cell.getCellTypeEnum(),获取单元格类型,case不同类型进行不同处理
            switch (cell.getCellTypeEnum()) {
                case _NONE: // 未知类型,用于表示初始化前的状态或缺少具体类型。仅供内部使用。
                    break;
                case NUMERIC: // 数字类型 小数,整数,日期

                    // 如果是数字类型的话,判断是不是日期类型
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date d = cell.getDateCellValue();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        cellValue = formatter.format(d);
                    } else if(cell.getCellStyle().getDataFormat() == 57) {
                        Date d = cell.getDateCellValue();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
                        cellValue = formatter.format(d);
                    } else {
                        DecimalFormat df = new DecimalFormat("0");
                        cellValue = df.format(cell.getNumericCellValue());
                    }

                    break;
                case STRING: // 字符串类型
                    cellValue = cell.getStringCellValue();
                    break;
                case FORMULA: // 公式类型
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                case BLANK: // 空白的单元格
                    break;
                case BOOLEAN: // 布尔类型
                    break;
                case ERROR: // 错误类型
                    break;
                default:
                    break;
            }
        }
        return cellValue;
    }
  • (5) Other types of information:
   public static String toStringValue(Cell cell) {
        if (cell != null) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            return cell.toString();
        } else {
            return "";
        }
    }
  • (6) test the entire functionality:

Prepare an Excel

 

 Analytical data are as follows:

At this point it's done.

Published 73 original articles · won praise 59 · views 30000 +

Guess you like

Origin blog.csdn.net/tangthh123/article/details/105230422