POI en utilisant les données d'analyse syntaxique Excel

Avant-propos:

vents mars ne soufflent pas loin la brume, puis laissez-le soleil Avril sur la terre, oubliez le passé, regard vers l'avenir. Au revoir Mars, bonjour Avril.

En utilisation récente de POI aux données d'importation à partir d'Excel à la base de données, alors je vais vous expliquer comment utiliser le POI.

Concept:

Apache POI est les bibliothèques open-source de la Fondation Apache Software, POI fournit une API au programme Java pour lire et écrire des fonctions de format de fichier Microsoft Office.

étapes:

  • (1) introduit dans le paquet de pot pom.xml.
  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>
  • (2) la première 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) l'interface back-end. 

  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 information de classe:
 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;
    }

En fait, je lis les données d'article dans Excel, quand il y a un problème qui toStringValue () Je vais lire les valeurs sont toutes converties en chaîne, Excel, s'il y a un type de champ de ligne est la valeur du temps, l' analyse syntaxique des données est un problème. J'ai utilisé les méthodes suivantes ne problématiques. Je réfère à cet article est

 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) Autres types d'informations:
   public static String toStringValue(Cell cell) {
        if (cell != null) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            return cell.toString();
        } else {
            return "";
        }
    }
  • (6) tester l'ensemble des fonctionnalités:

Préparer un fichier Excel

 

 Les données analytiques sont les suivantes:

À ce stade, il est fait.

Publié 73 articles originaux · éloge de won 59 · vues 30000 +

Je suppose que tu aimes

Origine blog.csdn.net/tangthh123/article/details/105230422
conseillé
Classement