Java后端解析Excel模板,获取模板数据内容

该文章介绍了一种Java后端通过ApachePOI库来动态获取Excel模板数据的方法,包括表头和内容的分离处理。代码示例展示了如何读取Excel文件,获取标题行和内容行,并将数据存储为Map结构。此外,文章提到了EasyExcel的依赖以及解析Excel数据的关键步骤。
摘要由CSDN通过智能技术生成

Java后端获取Excel模板数据

需要导入一个动态数据,不知道excel有多少项,每项内容是否都有值,所以简单点获取表的内容,
然后把表头和内容分开处理

模板样式

这个是根据现有的需求,做一个demo样式,如下图:

在这里插入图片描述
可以增加其他项,如下图增加了英语
在这里插入图片描述

代码工具类


import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * excel 导入获取模板数据
 */
@Slf4j
public class ExcelImportUtils {

    public static void main(String[] args) {
        Map<String,Object> map = getHeadersAndContents(null);
        System.out.println(map);
    }


    /**
     * 获取表头标题和内容信息
     * @param inputStream
     * @return
     */
    public static Map<String,Object> getHeadersAndContents(InputStream inputStream){
        Map<String,Object> tableMap = new HashMap<>();
        // 获取标题行title
        List<String> titleList = new ArrayList<>();
        // 获取内容
        List<Map<String,Object>> mapList = new ArrayList<>();
        Workbook workbook = null;
        try {
            // 测试用
            File file = new File("F:\\test_path\\importModel\\test.xlsx");
            inputStream = new FileInputStream(file);
//            inputStream = ExcelImportUtils.class.getResourceAsStream("/templates/checkTableImportModel.xlsx");

            List<T> list = new ArrayList<T>();
            //1.创建工作簿,使用excel能操作的这边都看看操作
            workbook = new XSSFWorkbook(inputStream);
            //2.得到表
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                throw new IOException("文件sheet不存在");
            }
            int rows = sheet.getPhysicalNumberOfRows();//获取sheet有多少行
            // 标题行有多少列
            Row row = sheet.getRow(1);
            int columns = row.getLastCellNum();

            // 遍历获取标题和行内容数据
            if (rows > 0) {
                // 获取标题
                for(int i=0;i<columns;i++){
                    Cell cell = row.getCell(i);
                    String title = getValue(cell);
                    if(!StringUtils.isEmpty(title)) {
                        titleList.add(title);
                    }
                }
                // 获取内容
                for(int r=2;r<rows;r++) {
                    Map<String,Object> map = new HashMap<>();
                    Row contentRow = sheet.getRow(r);
                    for (int i = 0; i < columns; i++) {
                        String title = getValue(row.getCell(i));
                        if(!StringUtils.isEmpty(title)) {
                            String content = getValue(contentRow.getCell(i));
                            map.put(title, content);
                        }
                    }
                    mapList.add(map);
                }

            }
            tableMap.put("titles",titleList);
            tableMap.put("contents",mapList);

            //4.得到数据后关流
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            log.info("读取excel文件内容失败!");
        }

        return tableMap;
    }

    public static String getValue(Cell cell){
        //匹配类型数据
        if (cell != null) {
            CellType cellType = cell.getCellTypeEnum();
            String cellValue = "";
            switch (cellType) {
                case STRING: //字符串
                    cellValue = cell.getStringCellValue();
                    break;
                case BOOLEAN: //布尔类型
                    cellValue = String.valueOf(cell.getBooleanCellValue());
                    break;
                case BLANK: //空
                    break;
                case NUMERIC: //数字(日期、普通数字)
                    if (HSSFDateUtil.isCellDateFormatted(cell)) { //日期
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        cellValue = dateFormat.format(date);
//                        cellValue = new DateTime(date).toString("yyyy-MM-dd");
                    } else {
                        //不是日期格式,防止数字过长
                        cell.setCellType(CellType.STRING);
                        cellValue = cell.toString();
                    }
                    break;
                case ERROR:
                    System.out.print("[数据类型错误]");
                    break;
            }
//            System.out.println(cellValue);
            return cellValue;
        } else {
            return "";
        }
    }

}

在这里插入图片描述

结果

这里我们已经可以拿到 数据,接下来就是根据表的结构,解析和处理数据就行

分析

1.主要用到的maven依赖

<!-- EasyExcel -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.7</version>
        </dependency>

2.代码解析注解

// 用于导入的excel文件
File file = new File("F:\\test_path\\importModel\\test.xlsx");
// 获取文件流
InputStream inputStream = new FileInputStream(file);
// 获取excel工作簿
Workbook workbook = new XSSFWorkbook(inputStream);
// 获取表单
Sheet sheet = workbook.getSheetAt(0);// 我这里只有一个sheet表单,也可以根据名字查询哪个表单
//获取sheet有多少行数据
int rows = sheet.getPhysicalNumberOfRows();
// 标题行有多少列
Row row = sheet.getRow(1);// 我的模板第一行是提示区,第二行是标题行[数据库字段]
int columns = row.getLastCellNum();

获取标题和内容

// 获取标题行title
List<String> titleList = new ArrayList<>();
// 获取内容
List<Map<String,Object>> mapList = new ArrayList<>();

// 遍历获取标题和行内容数据
if (rows > 0) {
	// 获取标题
	for(int i=0;i<columns;i++){
         Cell cell = row.getCell(i);
         String title = getValue(cell);
         if(!StringUtils.isEmpty(title)) {
             titleList.add(title);
         }
    }
    // 获取内容(我的是内容是从第三行开始的,所以是r=2)
    for(int r=2;r<rows;r++) {
        Map<String,Object> map = new HashMap<>();
        Row contentRow = sheet.getRow(r);
        for (int i = 0; i < columns; i++) {
            String title = getValue(row.getCell(i));
            if(!StringUtils.isEmpty(title)) {
            	String content = getValue(contentRow.getCell(i));
           		map.put(title, content);// 我这里为了方便查看是哪个列的数据,可以自己设计接收方式
            }
       }
       mapList.add(map);
    }
}

业务方面,根据获取到的数据进行处理即可。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值