POI 操作Excel导入篇1 -- 基本架构

本篇收录针对于POI导入Excel的操作sheet的一些常用步骤。

从网页导入文件到后台处理获得sheet

基本架构搭建(SpringBoot+HTML+MySQL)

  • 上传组件
 
     
  • ajax发送表单数据
var formdata = new FormData($("#uploadForm")[0]);
if (fileType !== 0) {
    $.ajax({
        type: 'post',
        url: ajaxUrl,
        data: formdata,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(res) {

},
        error: function(XHR) {

}
    });
}
  • 后台maven依赖
        //省略部分SpringBoot依赖
        
            org.apache.poi
            poi-ooxml
            3.9
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
            org.springframework.boot
            spring-boot-starter-logging
        
        
            commons-io
            commons-io
            2.4
        
  • 获取表单数据
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam(value = "excel",required = false) MultipartFile excel) throws Exception {
        String fileName = excel.getOriginalFilename();
        return excelService.insert(fileName, excel);
}
  • 获取文件sheet
public static Sheet checkExcelVersion(String fileName, MultipartFile file) throws Exception {
        //版本验证
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new RuntimeException("上传文件格式不正确");
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        is = file.getInputStream();
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        //返回第一个sheet
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        return sheet;
    }
  • 拓展(常用)
Workbook
Excel表格sheet的顶层对象
getActiveSheetIndex() 获取当前工作表中活动的工作表
getSheetAt(int index) 获取给定索引处的工作表对象。
getSheetIndex(Sheet sheet) 返回给定工作表的索引
getSheetName(int sheet) 获取工作表名称
Sheet
Workbook下的sheet工作表,包含单元格
getFirstRowNum() 获取工作表的第一行
getLastRowNum() 获取工作表有内容的最后一行
getPhysicalNumberOfRows() 返回已定义工作行的行数
getRow(int rownum) 返回索引起的逻辑行
isColumnHidden(int columnIndex) 判断索引处列是否为隐藏列

 

 

 

 

 

你可能感兴趣的:(JavaWeb,SpringBoot)