前面两篇文章实现了 Excel 文件的上传和下载。感兴趣的小伙伴可以点击链接看一下:
SpringBoot项目中集成EasyExcel实现Excel文件上传至MySQL
SpringBoot项目中集成EasyExcel实现Excel文件的下载
那一版本中,又有另一条需求。前端上传 .json
文件进来,不是上传 Excel
,好吧。。。
那我就兵来将挡水来土掩。直接解析 .json
文件不就完事了。所以直接就开干了。
1、contrller 层
@RestController
public class EasyExcelController {
private static final Logger LOGGER = LoggerFactory.getLogger(EasyExcelController.class);
@Autowired
private EasyExcelDao easyExcelDao;
@PostMapping(value = "/uploadFileFromJson",produces = "application/json;charset=UTF-8")
public ResponseEntity<ReturnT<String>> uploadFileFromJson(@RequestParam(value = "mappingFile") MultipartFile mappingFile) {
if (mappingFile == null) {
return new ResponseEntity<>(new ReturnT<>(ReturnT.BAD_REQUEST, "Params can not be null"), HttpStatus.BAD_REQUEST);
}
InputStream is = null;
BufferedReader br = null;
StringBuffer sb = new StringBuffer();
String str = null;
try {
is = mappingFile.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((str = br.readLine()) != null) {
sb.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
JSONObject jsonObject = JSONObject.parseObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("data");
List<EasyExcelData> eeDataList = JSONObject.parseArray(jsonArray.toJSONString(), EasyExcelData.class);
int count = 0;
try {
count = easyExcelDao.uploadFileFromJson(eeDataList);
} catch (Exception e) {
e.printStackTrace();
}
if (count <= 0) {
LOGGER.warn("no data to upload");
return new ResponseEntity<>(new ReturnT<>(ReturnT.BAD_REQUEST, "no data to upload"), HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(new ReturnT<>("successfully imported " + count + " pieces of data"), HttpStatus.OK);
}
}
由于 service
业务层比较简单,我这里直接操作 dao
层了。
2、EasyExcelDao
public interface EasyExcelDao {
int uploadFileFromJson(@Param("eeDataList") List<EasyExcelData> eeDataList);
}
3、EasyExcelMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.riemann.springbootdemo.dao.EasyExcelDao" >
<sql id="BASE_TABLE">
easy_excel_data
</sql>
<insert id="uploadFileFromJson" parameterType="com.riemann.springbootdemo.model.EasyExcelData">
<selectKey keyProperty="pid" resultType="long">
select LAST_INSERT_ID()
</selectKey>
INSERT INTO
<include refid="BASE_TABLE"/>
(
name,sex,age,address,phone
)
VALUES
<foreach collection="eeDataList" item="eeDataList" separator=",">
(
#{eeDataList.name, jdbcType=VARCHAR},
#{eeDataList.sex, jdbcType=INTEGER},
#{eeDataList.age, jdbcType=VARCHAR},
#{eeDataList.address, jdbcType=INTEGER},
#{eeDataList.phone, jdbcType=VARCHAR}
)
</foreach>
</insert>
</mapper>
4、测试
(1)、准备一个 .json
文件
扫描二维码关注公众号,回复:
8726309 查看本文章
(2)、浏览器请求:http://localhost:8080/uploadFileFromJson
(3)、查看数据库
ok,成功解析 .json
文件,同时上传至 MySQL
数据库了。