这两天在忙这个工作没写博客 刚干完活过来总结了
过程就是把上传的excel数据存到mysql 没什么难的 就是一些细节需要注意
1.首先 上传的MultipartFile转换成我们要读取的File
//file是上传的MultipartFile
File file2 = new File(fileUrl+file.getOriginalFilename()); //生成一个新文件
FileUtils.copyInputStreamToFile(file.getInputStream(), file2);
此时file2就成了我们想要的Flie 文件也上传到了对应路径下
2.读取文件中的数据类型不同
我为了方便都转成了string型
//cell就是Cell型 单元格
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
RichTextString richStringCellValue = cell.getRichStringCellValue();
String value = richStringCellValue.getString();
3.目标和工具类
我要读的excel如下图所示 我要保存的数值不一定是我程序直接读取的数值 而是在表格中直接看到的数值 我上网查那些办法都没解决 什么formdata方法根本没有 有大神路过可以给我留言
我是通过单位读出来的 好在只有两种单位 四舍五入 元/千克 保留两位 元/吨 取整
工具类下载地址
https://download.csdn.net/download/qq_35653822/10923812
4.不规则时间转换
看到了一个很强大的工具类 把不规则时间转换成yyyy-MM-dd HH:mm:ss格式
https://blog.csdn.net/summer7611/article/details/70174198
但是如果像我一样 2018年9月 就要自己先拼个1日或n日再去转换
5.数据统一处理
@PreUpdate @PrePersist hibernate jpa 注解
用这两个更新 存储注解对数据进行统一处理 比如转换时间啊 四舍五入数据啊
这个贴个代码看一下吧 里边 DateUtil.changeRegularTime 就是上边说的不规则时间转换方法
//三个价格 看单位 单位是 元/吨 就不保留小数 单位是 元/千克 就保留小数
@PreUpdate
@PrePersist
public void setValue(){//更新和添加之前都调用这个
double parseDouble = Double.parseDouble(this.localPrice);
double parseDouble2 = Double.parseDouble(this.foreignPrice);
double parseDouble3 = Double.parseDouble(this.differencePrice);
if("元/吨".equals(this.unit)){//四舍五入取整
this.localPrice = String.valueOf(Math.round(parseDouble));
this.foreignPrice = String.valueOf(Math.round(parseDouble2));
this.differencePrice = String.valueOf(Math.round(parseDouble3));
}else{//四舍五入保留两位
this.localPrice = String.valueOf((double)Math.round(parseDouble*100)/100);
this.foreignPrice = String.valueOf((double)Math.round(parseDouble2*100)/100);
this.differencePrice = String.valueOf((double)Math.round(parseDouble3*100)/100);
}
//转换规则时间格式
//如果2019年1月形式 后边在拼个1日
if(this.date.contains("年") && this.date.contains("月") && !this.date.contains("日")){
this.regularTime = DateUtil.changeRegularTime(this.date+"1日");
}else{//日期只有两种形式 2019年1月 2018.11.2
this.regularTime = DateUtil.changeRegularTime(this.date);
}
}
6.字段是Mysql关键字
这个之前也遇到过 在这记录一下
@Column(name="`date`")
private String date;
网上还有说 写成"\"date"\" 或者[date]的 没亲自试 感兴趣可以试试
还有 ` 这个符号 在键盘上~下边 之前我都没找到
7.list按照字符串日期排序lambda
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//正序返回给前端
list.sort((a,b)->{
try {
return sdf.parse(a.getRegularTime()).compareTo(sdf.parse(b.getRegularTime()));
} catch (ParseException e) {
throw new TRSSearchException("HaiguanColumn时间转换出错",e);
}
});
list.sort和Collections.sort
1.都要用Comparator匿名内部类
2.list.sort 入参一个 new Comparator
3.Collections.sort入参两个,new Comparator和list
https://blog.csdn.net/VICHOU_FA/article/details/80431785/
8.补充pom(注意jar包别冲突)
<!-- 引入poi,解析workbook视图 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>