Excel数据解析

Excel解析

pom文件导入jar包

       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.0</version>
        </dependency>

Controller层代码

@Slf4j
@RestController
@RequestMapping(value = "/excel")
@Api(tags = "excel",description = "数据解析")
public class ExcelController {

    @Autowired
    private ExcelService excelService;

    @PostMapping("/import")
    @ApiOperation(value = "解析Excel文件",notes = "解析Excel文件",httpMethod = "POST")
    public Response thermFactory(@RequestParam("file")MultipartFile file){
        return new Response.Builder()
                .withResult(excelService.analyzeData(file))
                .build();
    }
}

Service层代码

同时在代码中进行事务管理,如果导入的Excel表格中或者数据库中有相同的数据则进行手动回滚,并提示相同的数据

@Autowired
    private CustomerDAO customerDAO;

    @Transactional(rollbackFor = Exception.class)
    public List<String> analyzeData(MultipartFile file) {
        try(InputStream stream = file.getInputStream()) {
            Workbook wb = new XSSFWorkbook(stream);
            Sheet sheet = wb.getSheetAt(0);
            List<ThermFactoryPO> list = new ArrayList<>();
            int firstRowIndex = sheet.getFirstRowNum() + 1;
            int lastRowIndex = sheet.getLastRowNum();
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) {
                Row row = sheet.getRow(rIndex);
                if (row != null) {
                    ThermFactoryPO thermFactoryPO = new ThermFactoryPO();
                    ArrayList<String> strings = new ArrayList<>();
                    int firstCellIndex = row.getFirstCellNum();
                    int lastCellIndex = row.getLastCellNum();
                    for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) {
                        Cell cell = row.getCell(cIndex);
                        if (cell.getCellType() == CellType.STRING) {
                            strings.add(cell.toString());
                        } else if (cell.getCellType() == CellType.NUMERIC) {
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                strings.add(simpleDateFormat.format(cell.getDateCellValue()));
                            } else {
                                long numericCellValue = (long)cell.getNumericCellValue();
                                strings.add(numericCellValue + "");
                            }
                        }
                    }
                    thermFactoryPO.setImportTime(simpleDateFormat1.format(System.currentTimeMillis()));
                    thermFactoryPO.setThermId(strings.get(0));
                    thermFactoryPO.setModel(strings.get(1));
                    thermFactoryPO.setSsid(strings.get(2));
                    thermFactoryPO.setFactory(strings.get(3));
                    thermFactoryPO.setDeliveryTime(strings.get(4));
                    thermFactoryPO.setThermMac(strings.get(5));
                    thermFactoryPO.setPassword(strings.get(6));
                    thermFactoryPO.setSocketurl(strings.get(7));
                    thermFactoryPO.setLiences(strings.get(8));
                    list.add(thermFactoryPO);
                }
            }
            excelDAO.save(list);
            List<String> thermIds = excelDAO.getIds();
            if (thermIds.size() != 0){
               //手动回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return thermIds;
            }else {
                return new ArrayList<String>();
            }
        } catch (IOException e) {
            log.error("file parse error:{}", e.getMessage());
        }
        return null;
    }

Dao层代码

 /**
     * 保存表格信息
     * @param list
     * @return
     */
     int save(@Param("list")List<ThermFactoryPO> list);

     /**
      * 判断导入的数据,是否重复
      * @param
      * @return
      */
      List<String> getIds();

Mapper文件

 <insert id="save" parameterType="com.hr.admin.po.ThermFactoryPO" >
        INSERT INTO thermostatfactory(therm_id,therm_mac,model,ssid,password,factory,delivery_time) VALUES
        <foreach collection="list" item="factoryPO" separator=",">
            (#{factoryPO.thermId},#{factoryPO.thermMac},#{factoryPO.model},#{factoryPO.ssid},#{factoryPO.password},#{factoryPO.factory},#{factoryPO.deliveryTime})
        </foreach>
    </insert>

<select id="getIds" resultType="java.lang.String">
      select therm_id from thermostatfactory group by therm_id having count(therm_id) >1;
    </select>

实体类

@Data
public class ThermFactoryPO {
    private String deliveryTime;

    private String factory;

    private String model;

    private String password;

    private String ssid;

    private String thermId;

    private String thermMac;

    private Long id;
}

注意点

导入的Excel表格中数据列要和service层中的代码进行对应,否则将导致导入错误或者数据错乱。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ExMod Serial Assistant使用说明 ExMod串口调试助手主要功能是发送大量串口数据,设计目标是满足上位机串口编程调试之用,是个人把在上位机编程中常用的模拟调试功能汇总到一个调试软件中而成。除普通串口调试助手功能外,还包括发送文件中数据、Modbus Rtu Master常用功能。其中文件格式支持Excel、CSV、文本文件3种格式。配合虚拟串口软件,只要确定了通讯协议,即可脱离设备调试软件。可适用于自定义协议、Modbus Rtu协议。 使用说明: 软件主界面包括3个功能区,“发送任意串口数据”以上为功能区1,用于基本串口数据发送,还包括计算CRC校验码并与数据同时发送功能。 功能区2 包括“读取Holding寄存器”、“读取输入寄存器”、“写入多个寄存器”,用于单条Modbus数据读取、发送。 剩余部分为第3功能区,“发送文件中数据”用于大量串口数据发送。其下有多个发送选项,包括发送范围、发送间隔、数据格式。“延时”用于设置多条数据间发送间隔。“Modbus数据”选择表示文件中数据按Modbus格式发送,不选择表示为普通串口数据。如果文件中所有数据为同一寄存器地址,需在“寄存器地址”中输入地址,如果多条数据地址不同,可在文件中编辑寄存器地址,此时需选择“第一列为地址”。Excel、CSV中第一列好理解,文本文件在软件中也按CVS格式处理,即文本文件中第1个逗号之前视为第一列。 发送文件中数据如果选择“Modbus数据”,仅支持“WriteMultipleRegisters”命令发送。发送串口数据如果16进制数据不为整字节(Modbus时为整字),会在数据前补0。 接收数据中的显示内容如果长度超过0.1M会自动保存到以当前时间命名的文本文件中。也可以手动保存以便以后调试时使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值