poi导入工具类

poi导入工具类 (poi版本3.17)

Java7后,在 try{} 代码块中的流 会自动关闭
在这里插入图片描述

导入工具类

	/**
     * 导入excel,解析数据
     * @param file file传输excel文件
     * @param keyList 表头所对应实体类的key值
     * @return
     */
    public static String importExcel(MultipartFile file,List<String> keyList){
        try{
            if(!file.isEmpty()){
                List<Map<String,Object>> dataMapList = new ArrayList<>();

                XSSFWorkbook wb = new XSSFWorkbook(file.getInputStream());
                XSSFSheet sheet = wb.getSheetAt(0);
                XSSFRow titleRow = sheet.getRow(0);
                //内容存在的最后一格单元格数量,从0开始
                int lastCellNum = titleRow.getLastCellNum();
                //内存存在的最后一行数量,从0开始
                int lastRowNum = sheet.getLastRowNum();
                //excel内容从1开始
                for (int a = 1; a < lastRowNum; a++) {
                    XSSFRow row = sheet.getRow(a);
                    //key,value形式存储
                    Map<String, Object> dataMap = new HashMap<>();
                    for (int b = 0; b < lastCellNum; b++) {
                        //获取每行单元格
                        XSSFCell cell = row.getCell(b);
                        //将cell中的类型转换为String类型
                        cell.setCellType(CellType.STRING);
                        //读取excel中value
                        String cellValue = StringUtils.isNotBlank(cell.getStringCellValue()) ? cell.getStringCellValue().trim() : "";
                        //key
                        String key = keyList.get(b);
                        //存入dataMap中
                        dataMap.put(key,cellValue);
                    }
                    //存入list
                    dataMapList.add(dataMap);
                }
                return JSON.toJSONString(dataMapList);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

Controller代码如下

将jsonStr 转为自己所需要的 对象集合数据, 可以根据各位的需求 自行处理

	/**
	 * 导入产品规格信息
	 * @param attach
	 * @return
	 */
	@RequestMapping("/importExcel")
	public R importExcel(@RequestParam("file") MultipartFile attach) {
		try{
			//数据集合
			List<String> keyList = Arrays.asList("productName", "model", "power", "isWaterproof", "rotateOrStatic", "color", "isRemoteControl", "schedulingName", "specWeight", "costPrice", "sellingPrice");
			//读取完excel数据后 得到的 对象集合
			String jsonStr = ExcelUtils.importExcel(attach, keyList);
			List<NProductSpecEntity> dataList = JSON.parseArray(jsonStr, NProductSpecEntity.class);

			return R.ok().put("dataList",dataList);
		}catch (Exception e){
			e.printStackTrace();
		}finally {

		}
		return R.error();
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用Apache POI导入Excel的Java工具类示例: ```java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelUtils { /** * 读取Excel文件,返回一个二维数组 * * @param filePath Excel文件路径 * @param sheetName 工作表名称 * @return 二维数组 * @throws IOException */ public static String[][] readExcel(String filePath, String sheetName) throws IOException { Workbook workbook = null; InputStream inputStream = new FileInputStream(filePath); if (filePath.endsWith(".xls")) { workbook = new HSSFWorkbook(inputStream); } else if (filePath.endsWith(".xlsx")) { workbook = new XSSFWorkbook(inputStream); } else { throw new RuntimeException("不支持的文件格式"); } Sheet sheet = workbook.getSheet(sheetName); int rowCount = sheet.getPhysicalNumberOfRows(); int columnCount = sheet.getRow(0).getPhysicalNumberOfCells(); String[][] data = new String[rowCount - 1][columnCount]; for (int i = 1; i < rowCount; i++) { Row row = sheet.getRow(i); for (int j = 0; j < columnCount; j++) { Cell cell = row.getCell(j); data[i - 1][j] = cell.toString(); } } workbook.close(); inputStream.close(); return data; } } ``` 使用示例: ```java String filePath = "path/to/excel/file.xlsx"; String sheetName = "Sheet1"; String[][] data = ExcelUtils.readExcel(filePath, sheetName); ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值