一、安装 axios

1.1 安装 axios

npm install axios -S

1.2 安装 vue-axios

npm install vue-axios -S

package.json 中的 dependencies检查是否成功安装好。

1.3 全局引入 axios

main.jsimport 和引入。

  1. import axios from 'axios'
  2. const app = createApp(App)
  3. // 引入
  4. app.config.globalProperties.$axios = axios

二、编写上传界面

  1. <template>
  2. <el-upload
  3. ref="uploadRef"
  4. class="upload-demo"
  5. action="/uploadExcel"
  6. accept=".xls,.xlsx,.csv"
  7. :on-success="handleFileUploadSuccess"
  8. :on-change="handleChange"
  9. :before-upload="handleBeforeUpload"
  10. :auto-upload="false"
  11. :limit="5"
  12. :file-list="fileList"
  13. >
  14. <template #trigger>
  15. <el-button type="primary">选择 Excel 文件</el-button>
  16. </template>
  17. <el-button class="ml-3" type="success" @click="submitUpload">
  18. 生成
  19. </el-button>
  20. </el-upload>
  21. </template>
  22. export default {
  23. name: 'App',
  24. components: {
  25. HelloWorld
  26. },
  27. data(){
  28. return {
  29. fileList: [], // 定义一个空数组
  30. }
  31. },
  32. methods: {
  33. /**
  34. * 上传之前的处理
  35. * @returns {boolean}
  36. */
  37. handleBeforeUpload(rawFile) {
  38. return true;
  39. },
  40. /**
  41. * 上传成功的处理
  42. */
  43. handleFileUploadSuccess(file){
  44. },
  45. /**
  46. * 提交上传的文件
  47. */
  48. submitUpload(){
  49. // 判断是否有文件再上传
  50. if (this.fileList.length === 0) {
  51. return this.$message.warning('请选取文件后再上传')
  52. }
  53. // 下面的代码将创建一个空的 FormData 对象:
  54. const formData = new FormData();
  55. // 参数的键名为 'file'
  56. this.fileList.forEach((file) => {
  57. formData.append('file', file.raw);
  58. })
  59. // 通过 axios 进行上传
  60. // uploadExcelFile 后端处理的路径
  61. this.params = formData;
  62. axios({
  63. method: 'post',
  64. url: 'http://localhost:8080/uploadExcelFile',
  65. data: this.params,
  66. headers: {
  67. 'Content-Type': 'application/x-www-form-urlencoded'
  68. }
  69. })
  70. },
  71. /**
  72. * 过滤上传的文件类型
  73. */
  74. handleChange(file, fileList){
  75. if (!/\.(xlsx|xls|XLSX|XLS|csv)$/.test(file.name)) {
  76. this.$message({
  77. type: 'warning',
  78. message: '上传文件只能为 Excel 文件!'
  79. })
  80. this.fileList = []
  81. return false
  82. }
  83. // 手动上传需要保存 file.raw
  84. this.file = file.raw
  85. }
  86. }
  87. }
  88. </script>

三、后端处理 Post 请求

3.1 后端处理函数

  1. @CrossOrigin
  2. @Controller
  3. public class ExcelController {
  4. @Autowired
  5. private UploadDAO uploadDAO;
  6. /**
  7. * 读取用户上传过来的 Excel 文件
  8. * @param file 上传的 Excel 文件
  9. * @param response
  10. */
  11. @PostMapping(value = "/uploadExcelFile")
  12. @ResponseBody
  13. public void readUploadExcel(@RequestParam("file") MultipartFile file) throws IOException {
  14. EasyExcel.read(file.getInputStream(), ExcelEntity.class, new ExcelEntityListener(uploadDAO)).sheet(0).doRead();
  15. }
  16. }

file 就是传递过来的 Excel 文件。

为了获取到 Excel 里面的值,我们还需要一个 Excel 处理框架,我选择了阿里的 easyExcel

3.2 添加 dependency

  1. <!-- 导入 easyexcel 用来做 excel 处理-->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>easyexcel</artifactId>
  5. <version>3.0.5</version>
  6. </dependency>
  1. <dependency>
  2. <groupId>com.alibaba</groupId>
  3. <artifactId>fastjson</artifactId>
  4. <version>1.2.80</version>
  5. </dependency>

一块添加 fastjson后面会用来处理获取到的数据,把它 json化。

3.3 创建 Excel 文件的实体类 ExcelEntity.java

  1. @Data
  2. public class ExcelEntity{
  3. @ExcelProperty("订单号")
  4. private String orderId; // 订单号
  5. private String externalOrderId; // 外部订单号
  6. private String orderCommodityState; // 重要:订单商品状态:「待发货」
  7. private Date tradeSuccessTime; // 交易成功时间
  8. private String commodityName; // 重要:商品名称
  9. private String commodityType; // 商品类型
  10. private String commodityCategory; // 商品类目
  11. private String commoditySpecification; // 重要:商品规格
  12. private String specificationCode; // 规格编码, 默认为 ""
  13. private String commodityCode; // 商品编码,默认为 ""
  14. private double commodityUnitPrice; // 商品单价
  15. private String commodityCostPrice; // 商品成本价
  16. private String commodityPromotionMethod; // 商品优惠方式
  17. private double commodityPromotionAfterPrice; // 商品优惠后价格
  18. private int commodityNumber; // 重要:商品数量
  19. private double commodityMoneyTotal; // 商品金额小计
  20. private String shopPromotion; // 店铺优惠
  21. private String commodityActualDealPrice; // 商品实际成交金额
  22. private String commodityCreditIntegralNumber; // 商品抵用积分数
  23. private String commodityMessage; // 商品留言
  24. private String consignee; // 重要:收货人
  25. private String consigneeTel; // 重要:收货人手机号
  26. private String consigneeProvince; // 重要:收货人所在省份
  27. private String consigneeCity; // 重要:收货人所在城市
  28. private String consigneeDistrict; // 重要:收货人所在地区
  29. private String consigneeDetailAddress; // 重要:收货人所在地址
  30. private String buyerRemark; // 买家备注
  31. private String commodityShipState; // 商品发货状态
  32. private String commodityShipStyle; // 商品发货方式
  33. private String commodityShipLogisticsCompany; // 商品发货物流公司
  34. private String commodityShipLogisticsId; // 商品发货物流单号
  35. private String commodityShipEmployee; // 发货员工
  36. private Date commodityShipTime; // 发货时间
  37. private String commodityRefundState; // 商品退款状态
  38. private String commodityRefundMoney; // 商品已退款金额
  39. private String businessmanOrderRemark; // 商家订单备注
  40. private Date checkInTime; // 入住时间
  41. }

这个会将 Excel 文件中列的数据与类的字段绑定在一块,按照声明的顺序,如果不想按照顺序可以使用 @ExcelProperty("列名")来绑定在一块。

3.4 创建 ExcelEntityListener.java 监听器

  1. /**
  2. *
  3. * @Author 云胡
  4. * @Description Excel 工具类
  5. * @Date 2022-04-15
  6. */
  7. @Slf4j
  8. public class ExcelEntityListener implements ReadListener<ExcelEntity> {
  9. public ExcelEntityListener(UploadDAO uploadDAO) {
  10. this.uploadDAO = uploadDAO;
  11. }
  12. /**
  13. * 这个每一条数据解析都会来调用
  14. *
  15. * @param context
  16. */
  17. @Override
  18. public void invoke(ExcelEntity data, AnalysisContext context) {
  19. log.info("解析到一条数据:{}", JSON.toJSONString(data));
  20. }
  21. /**
  22. * 所有数据解析完成了 都会来调用
  23. * @param context
  24. */
  25. @Override
  26. public void doAfterAllAnalysed(AnalysisContext context) {
  27. log.info("所有数据解析完成!");
  28. }
  29. }

3.5 创建 UploadDao.java

  1. @Repository
  2. public class UploadDAO {
  3. public void save(List<ExcelEntity> list) {
  4. // 如果是mybatis,尽量别直接调用多次insert,自己写一个mapper里面新增一个方法batchInsert,所有数据一次性插入
  5. }
  6. }

目前没有使用,后续可以存到数据库里。

四、结果展示

4.1 本地 Excel 测试数据

订单号 外部订单号 订单商品状态 交易成功时间 商品名称 商品类型 商品类目 商品规格 规格编码 商品编码 商品单价 商品成本价 商品优惠方式 商品优惠后价格 商品数量 商品金额小计 店铺优惠(分摊) 商品实际成交金额 商品抵用积分数 商品留言 收货人/提货人 收货人手机号/提货人手机号 收货人省份 收货人城市 收货人地区 详细收货地址/提货地址 买家备注 商品发货状态 商品发货方式 商品发货物流公司 商品发货物流单号 发货员工 商品发货时间 商品退款状态 商品已退款金额 商家订单备注 入住时间
E20220331142238091806171 C1728795398635640 待发货 Muchshow美腹贴 塑形新科技 普通类型商品 其他 美腹贴女士2盒 278.8 278.8 1 278.8 69.20(分销商等级折扣:47.80) 348 0 孙悟空 13666666666 云南省 昆明市 盘龙区 云南省昆明市盘龙区佛寺 未发货 快递 0
E20220330182239081300015 C1728719896969425 待发货 【环保袋中的爱马仕】德国单肩时尚环保袋 超轻便携 创意礼品 博物馆系列 普通类型商品 其他 麦田 73.5 73.5 1 73.5 24.50(分销商等级折扣:9.80) 98 0 猪八戒 13999999999 山东省 淄博市 张店区 山东省淄博市张店区佛寺 未发货 快递 0

4.2 上传

image.png
点击选择 Excel 文件,将本地 Excel 文件上传,然后点击生成。

4.3 log 输出的 Excel 数据

  1. 2022-04-15 18:40:29.964 INFO 17068 --- [nio-8080-exec-1] c.e.c.Util.ExcelEntityListener : 解析到一条数据:{"commodityActualDealPrice":"348","commodityCategory":"其他","commodityCreditIntegralNumber":"0","commodityMoneyTotal":278.8,"commodityName":"Muchshow美腹贴 塑形新科技","commodityNumber":1,"commodityPromotionAfterPrice":278.8,"commodityRefundMoney":"0","commodityShipState":"未发货","commodityShipStyle":"快递","commoditySpecification":"美腹贴女士2盒","commodityType":"普通类型商品","commodityUnitPrice":278.8,"consignee":"孙悟空","consigneeCity":"昆明市","consigneeDetailAddress":"云南省昆明市盘龙区佛寺","consigneeDistrict":"盘龙区","consigneeProvince":"云南省","consigneeTel":"13666666666","externalOrderId":"C1728795398635640","orderCommodityState":"待发货","orderId":"E20220331142238091806171","shopPromotion":"69.20(分销商等级折扣:47.80)"}
  2. 2022-04-15 18:40:29.967 INFO 17068 --- [nio-8080-exec-1] c.e.c.Util.ExcelEntityListener : 解析到一条数据:{"commodityActualDealPrice":"98","commodityCategory":"其他","commodityCreditIntegralNumber":"0","commodityMoneyTotal":73.5,"commodityName":"【环保袋中的爱马仕】德国单肩时尚环保袋 超轻便携 创意礼品 博物馆系列","commodityNumber":1,"commodityPromotionAfterPrice":73.5,"commodityRefundMoney":"0","commodityShipState":"未发货","commodityShipStyle":"快递","commoditySpecification":"麦田","commodityType":"普通类型商品","commodityUnitPrice":73.5,"consignee":"猪八戒","consigneeCity":"淄博市","consigneeDetailAddress":"山东省淄博市张店区佛寺","consigneeDistrict":"张店区","consigneeProvince":"山东省","consigneeTel":"13999999999","externalOrderId":"C1728719896969425","orderCommodityState":"待发货","orderId":"E20220330182239081300015","shopPromotion":"24.50(分销商等级折扣:9.80)"}
  3. 2022-04-15 18:40:29.968 INFO 17068 --- [nio-8080-exec-1] c.e.c.Util.ExcelEntityListener : 所有数据解析完成!