当前位置:   article > 正文

【uniapp】使用uniapp和springboot导出excel_uniapp 使用luckysheet

uniapp 使用luckysheet

流程:
在这里插入图片描述

注:遇到了一个大坑,这种方式目前只适用于idea直接跑的,打包成jar包之后就行不通了,目前还没有解决,希望大神们可以指导一下。
前端代码:

 exportExcel(e){
			 //将excel写到target文件中
				 uni.request({
				 //访问后端接口,后端生成excel
				 	url:getApp().globalData.url+"/dhTask/exportExcelByProTaskId",
				 	data:{proTaskId:this.production_task_id},
				 	method:"POST",
				 	header: { 'content-type':'application/x-www-form-urlencoded' ,'Authorization': uni.getStorageSync("token")},
				 	success: (res) => {
				 				var data=res.data.data
				 				if(res.data.code==200){
									console.log(" 后端返回的结果:  "+res.data.data)
									//如果后端返回的结果是1,
									if(res.data.data==1){
										uni.downloadFile({
										//这里访问的是后端开放的静态资源路径
															  url: getApp().globalData.url+'/excel/'+this.production_task_id+'.xls', 
														    success: (res) => {
																	console.log(res)
																	let xlsFilePath=res.tempFilePath
																		uni.saveFile({
																	    tempFilePath:xlsFilePath,
																		success:(res)=>{
																			 // res.savedFilePath文件的保存路径
																			 //保存成功并打开文件
																			 uni.openDocument({
																				filePath:res.savedFilePath,
																				success:(res)=>{
																					console.log('成功打开文档')
																					this.getajax4("/dhTask/deleteExcel",{production_task_id:this.production_task_id},'post',function(a,b){
																						
																					})
																				}
																				
																			})
																		},
																		fail:()=>console.log('下载失败')
																	})				
														    }
														});
														
									}
				 					
				 					}
				 	},error(){
				 		uni.showToast({title:"操作失败1!", icon:"none"});
				 		return 0
				 	}
				 	
				 })	

			},





  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

后端代码:

依赖

<dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

静态资源映射路径配置

这个类是用来配置跨域问题的,实现了WebMvcConfigurer 接口,所以可以重写addResourceHandlers,所以就将addResourceHandlers写在这里了

package com.fusdom.config;

import com.fusdom.utils.XmlUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.io.FileNotFoundException;

//@Configuration注解
@Configuration
//实现WebMvcConfigurer
public class CrossDomainConfig implements WebMvcConfigurer {
    //重写addCorsMappings方法:这个是用来解决跨域问题的
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "OPTIONS")
                .maxAge(3600);

    }


//静态资源映射路径配置
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
        String path="";
        //这里是我用来处理jar包形式的
        if(XmlUtils.class.getResource("").toString().contains("jar:")){
        String projectPath = System.getProperty("user.dir");
            path=new File(projectPath+"/classes/static/asserts/img/excel/").getPath()+"\\".replace("\\","\\\\");
            //idea方式运行
        }else{
        //获取target下的文件的目录
        path = XmlUtils.class.getResource("/static/asserts/img/excel/").getPath().substring(1).replace("file:", "").replace("/",File.separator);
        }

registry.addResourceHandler("/excel/**").addResourceLocations("file:"+path);
//        registry.addResourceHandler("/excel/**").addResourceLocations("file:D:\\gitDownloader\\micro_services\\cloud_base\\target\\classes\\static\\asserts\\img\\excel\\");

        WebMvcConfigurer.super.addResourceHandlers(registry);

    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

controller层

 //导出对应批次任务id的excel表格
   @RequestMapping("/exportExcelByProTaskId")
   public Object exportExcelByProTaskId(String proTaskId) throws IOException {

       //此处获取对应的表格数据,可以自己写一个接口
       List<Map<String, Object>> list = dhTaskService.getMsgByBatchTaskId(Long.valueOf(proTaskId));

       /*
        * 使用java POI 创建excel文件,不清楚的话可以百度搜索一下如何使用
        * */
       //文档
       HSSFWorkbook wb = new HSSFWorkbook();
       //表单
       HSSFSheet sheet = wb.createSheet("批次任务表");
       //设置列宽度
       sheet.setColumnWidth(10, 20 * 256);
       sheet.setColumnWidth(11, 20 * 256);
       //表头
       HSSFRow row1 = sheet.createRow(0);
       row1.createCell(0).setCellValue("任务名称");
       row1.createCell(1).setCellValue("产品名称");
       row1.createCell(2).setCellValue("供应商");
       row1.createCell(3).setCellValue("参数名称");
       row1.createCell(4).setCellValue("等级");
       row1.createCell(5).setCellValue("等级名称");
       row1.createCell(6).setCellValue("下限");
       row1.createCell(7).setCellValue("上限");
       row1.createCell(8).setCellValue("数量");
       row1.createCell(9).setCellValue("重量");
       row1.createCell(10).setCellValue("任务开始时间");
       row1.createCell(11).setCellValue("任务结束时间");






       //行数据
       for (int i = 0; i < list.size(); i++) {
           HSSFRow row = sheet.createRow(i + 1);
           row.createCell(0).setCellValue(list.get(i).get("production_task_name").toString());
           row.createCell(1).setCellValue(list.get(i).get("product_name").toString());
           row.createCell(2).setCellValue(list.get(i).get("company_name").toString());
           row.createCell(3).setCellValue(list.get(i).get("param_name").toString());
           row.createCell(4).setCellValue(list.get(i).get("rank_num").toString());
           row.createCell(5).setCellValue(list.get(i).get("rank_name").toString());
           row.createCell(6).setCellValue(list.get(i).get("lower_limit").toString());
           row.createCell(7).setCellValue(list.get(i).get("upper_limit").toString());
           row.createCell(8).setCellValue(list.get(i).get("number").toString());
           row.createCell(9).setCellValue(list.get(i).get("weight").toString());
           row.createCell(10).setCellValue(list.get(i).get("start_time").toString());
           row.createCell(11).setCellValue(list.get(i).get("end_time").toString());


       }

//我这里是生成在target/classes下的文件路径的,所以处理的很麻烦,
//建议大家可以写在固定的路径下,这样子处理就会容易很多了
       try {
           String target ="";
           File targetFile=null;
           //如果打包成jar包的形式
           if(XmlUtils.class.getResource("").toString().contains("jar:")){
               String projectPath = System.getProperty("user.dir");
               targetFile=new File(projectPath+"/classes/static/asserts/img/excel/"+ proTaskId + ".xls");
               System.out.println("生成文件的目录>>>"+targetFile);
//如果是以idea的方式运行
           }else{
               //获取target下的文件的目录
               target = XmlUtils.class.getResource("/static/asserts/img/excel").getPath().replace("file:", "");
               targetFile = new File(target + "/" + proTaskId + ".xls");
           }


   //文件输出流
           FileOutputStream targetOutput = new FileOutputStream(targetFile);
           //将文档写入流
           wb.write(targetOutput);
           //记得flush()
           targetOutput.flush();
           System.out.println(">>>>>>>>>>>>>>>>>执行完毕");
//关闭流
           wb.close();
           targetOutput.close();
           //这里是我自己写的一些返回前端的实体类,大家可以自己写
           return new CommonResult().success(1);
       } catch (Exception e) {
           return new CommonResult().success(-1);
       }
   }


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/264081
推荐阅读
相关标签
  

闽ICP备14008679号