文件打包下载excel导出和word导出

news/2024/7/21 4:13:26 标签: excel, word

0.文件下载接口

        请求 GET

        /pm/prj/menu/whsj/download/{affixId}

       文件affixId多个id以逗号隔开。多个文件会以打包得形式。

 

1.Excel导出

        1.0接口

POST

127.0.0.1:8400/pm/io/exportExcel/year-plan-table-workflow/report

参数

[{"org":"011","report":"年度计划表","fiscalYear":"2023","mofDivCode":"371000"}] 

 

    1.1配置模板

数据要以 [entity.object]为模板配置,而且下方必须空一行不然导入会报错

1.2导入模板配置导出配置

多个集合需要配置多个查询条件,配置得服务接口要跟代码里面得对应服务接口得代码

word">package com.wenzheng.whsj.prj.export;

word">import com.wenzheng.word">module.common.excel.suite.service.DataSourceProvider;
word">import com.wenzheng.platform.core.bean.LoginUser;
word">import com.wenzheng.whsj.prj.persistence.entity.YearPlanInfo;
word">import com.wenzheng.whsj.prj.service.PmPrjConcentrateArgumentService;
word">import org.springframework.beans.factory.annotation.Autowired;
word">import org.springframework.stereotype.Service;

word">import java.util.List;
word">import java.util.Map;

/**
 *
 * 年度计划表导出
 *
 * @Author ZRP
 * @Date 2023/10/13 14:36
 */
@Service(value = "gzw.yearPlanTableCloudProjectExport")
word">public word">class YearPlanTableCloudProjectExport word">implements DataSourceProvider {

	@Autowired
	word">private PmPrjConcentrateArgumentService pmPrjConcentrateArgumentService;


	@Override
	word">public List<Map<String, Object>> findData(Map<String, Object> param) {
		LoginUser user = word">new LoginUser();
		user.setFiscalYear(param.get("fiscalYear").toString());
		user.setMofDivCode(param.get("mofDivCode").toString());
		user.setOrgCode(param.get("org").toString());

		YearPlanInfo yearPlanInfo = pmPrjConcentrateArgumentService.selectYearPlan(0, user, null, null, null, null);
		word">return yearPlanInfo.getCloudProjectList();
	}
}

2.导出word

     2.0接口

年度计划书导出 接口

POST

http://10.30.4.96:8400/pm/io/exportExcel/year-plan-book-workflow/report

参数

[{"org":"011","report":"年度计划书","fiscalYear":"2023","mofDivCode":"371000"}]

   2.1模板

2.2配置模板

2.3编写替换数据代码

 @Autowired
    word">private PmTemplateAffixService templateAffixService;
    @Autowired
    word">protected SuiteExportService exportService;
    @Autowired
    word">private OfficeService officeService;
    @Value("${base.uploadpath:upload}")
    word">private String uploadPath;
    @Autowired
    word">private PmBaseAffixMapper affixMapper;
    @Autowired
    word">private FundsAnalysisService fundsAnalysisService;



@Override
    word">public ResponseEntity<byte[]> downloadWordReport(HttpServletRequest request, String id, Map<String, Object> params, LoginUser user) word">throws Exception {
        word">if (BaseUtils.isNull(id)) {
            word">return null;
        }
        word">if (org.apache.commons.collections4.MapUtils.isEmpty(params)) {
            params = word">new HashMap<>();
            params.put("fiscalYear", user.getFiscalYear());
            params.put("mofDivCode", user.getMofDivCode());
        }
        String useObject = exportService.getExpKeyByExportSwitch("year-plan-table-workflow-report", params, user.getFiscalYear(), user.getMofDivCode(), SuiteExportService.TYPE_WORD);
        // 取得模板
        List<PmTemplateAffix> lstTemplate = templateAffixService.selectByUseObject(useObject, user.getFiscalYear(),
                user.getMofDivCode());
        word">if (lstTemplate == null || lstTemplate.isEmpty()) {
            word">throw word">new TemplateSetException("模板没定义");
        }
        PmTemplateAffix affixTemp = lstTemplate.get(0);
        byte[] data = affixTemp.getFileData();
        //查询数据
        Map<String, Object> map = pmPrjMeasurementReferenceDao.selectById(id);
        word">if (map == null) {
            word">throw word">new TemplateSetException("暂无当前数据");
        }
        map = initData(map, user, request);
        String prjName = map.get("prj_name").toString();
        String fileName = prjName + affixTemp.getFileName().substring(0, affixTemp.getFileName().indexOf(".")) + "." + affixTemp.getFileType();


        // 替换
        data = officeService.createDoc(data, map);
        createFile(data, map, lstTemplate.get(0), fileName);



        //如果是生成的,则直接返回 如果是下载用下面这些代码直接输出文件流
        HttpHeaders headers = word">new HttpHeaders();
        // 处理文件名编码问题
        String userAgent = request.getHeader("user-agent");
        word">if (HttpUtils.isMSBrowser(userAgent)) {
            // 如果是IE浏览器,则用URLEncode解析
            fileName = URLEncoder.encode(fileName, "UTF-8");
            fileName = fileName.replace("+", " ");
        } word">else {
            // 如果是谷歌、火狐则解析为ISO-8859-1
            fileName = word">new String(fileName.getBytes("gbk"), StandardCharsets.ISO_8859_1);
        }
        headers.set("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        word">return word">new ResponseEntity<>(data, headers, HttpStatus.OK);
    }



//创建文件出来,存入文件库 获得文件要下载文件id
word">public String createFile(byte[] data, Map<String, Object> map, PmTemplateAffix pmTemplateAffix, String fileName) {
        String useObject = "yearPlanReport";
        DateFormat dateFormat = word">new SimpleDateFormat("yyyyMMdd");
        String dateStr = dateFormat.format(word">new Date());
        String uuidName = UUID.randomUUID().toString();
        String fileRealName = UUID.randomUUID().toString();

        File templateAffixFile = null;
        word">try {
            templateAffixFile = FileTool.fileToBytes(data, uploadPath + "/" + useObject + "/" + dateStr + "/", "/" + uuidName);
        } word">catch (Exception e) {
            System.err.println("===========>" + e.getMessage());
        }
        MultipartFile multipartFile = FileTool.getMultipartFile(templateAffixFile);
        PmBaseAffix affix = word">new PmBaseAffix();
        affix.setAffixId(UUID.randomUUID().toString());
        word">if (map.get("affix_id") != null) {
            affix.setPrjId(map.get("affix_id").toString());
        } word">else {
            affix.setPrjId(UUID.randomUUID().toString());
        }
        affix.setJobId(affix.getPrjId());
        affix.setUseObject(useObject);
        affix.setFileType(pmTemplateAffix.getFileType());
        affix.setFileSize(BaseUtils.sizeParse(multipartFile.getSize()));
        affix.setFileName(fileName);
        affix.setFileTitle(fileName);
        affix.setFileRealName(uuidName);
        affix.setFilePath(File.separator + affix.getUseObject() + File.separator + dateStr);
        affix.setUpdateTime(word">new Date());
        List<PmBaseAffix> pmBaseAffix = pmPrjMeasurementReferenceDao.selectByPrjCode(affix.getPrjId(), useObject);
        word">if (pmBaseAffix.size() == 0) {
            affixMapper.insert(affix);
        } word">else {
            affix.setAffixId(pmBaseAffix.get(0).getAffixId());
            affixMapper.updateByPrimaryKeySelective(affix);
        }
        word">return affix.getAffixId();
    }


用到的工具方法

/**
	 * 将Byte数组转换成文件
	 *
	 * @param bytes    byte数组
	 * @param filePath 文件路径  如 D:\\Users\\Downloads\\
	 * @param fileName 文件名
	 */
	word">public word">static File fileToBytes(byte[] bytes, String filePath, String fileName) {
		BufferedOutputStream bos = null;
		FileOutputStream fos = null;
		File file = null;
		word">try {
			file = word">new File(filePath + fileName);
			word">if (!file.getParentFile().exists()) {
				//文件夹不存在 生成
				file.getParentFile().mkdirs();
			}
			fos = word">new FileOutputStream(file);
			bos = word">new BufferedOutputStream(fos);
			bos.write(bytes);
		} word">catch (Exception e) {
			e.printStackTrace();
		} word">finally {
			word">if (bos != null) {
				word">try {
					bos.close();
				} word">catch (IOException e) {
					e.printStackTrace();
				}
			}
			word">if (fos != null) {
				word">try {
					fos.close();
				} word">catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		word">return file;
	}

	word">public word">static  MultipartFile getMultipartFile(File file) {
		FileInputStream fileInputStream = null;
		MultipartFile multipartFile = null;
		word">try {
			fileInputStream = word">new FileInputStream(file);
			multipartFile = word">new MockMultipartFile(file.getName(), file.getName(),
					ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
		} word">catch (Exception e) {
			e.printStackTrace();
		}
		word">return multipartFile;
	}


http://www.niftyadmin.cn/n/5099563.html

相关文章

事件循环(渡一)

一、事件循环 浏览器有哪些进程和线程 浏览器是一个多进程多线程的应用程序&#xff0c;当启动浏览器后&#xff0c;会默认启动多个进程 可以在浏览器任务管理器中查看所有进程 其中最主要的进程有&#xff1a; 浏览器进程 主要负责界面展示&#xff0c;用户交互&#xff0c;…

神奇的python的多线程

通过函数 import random import threading import timedef pr(num):for i in range(10):print(f"{num}: i:{i}")time.sleep(random.uniform(0, 1))t1 threading.Thread(targetpr, kwargs{"num": "t1"}) t2 threading.Thread(targetpr, kwarg…

站外引流之道:跨境电商如何吸引更多流量?

随着跨境电商行业的蓬勃发展&#xff0c;站外引流成为卖家们必须掌握的关键技能。站外引流不仅有助于扩大产品曝光度&#xff0c;还能吸引更多潜在客户&#xff0c;提高销售额。 然而&#xff0c;站外引流并非易事&#xff0c;需要精心策划和执行。本文将探讨站外引流的策略&a…

鸿蒙应用开发之HTTP数据请求

一、概述 日常生活中我们使用应用程序看新闻、发送消息等&#xff0c;都需要连接到互联网&#xff0c;从服务端获取数据。例如&#xff0c;新闻应用可以从新闻服务器中获取最新的热点新闻&#xff0c;从而给用户打造更加丰富、更加实用的体验。 那么要实现这样一种能实时从服务…

matlab中绘制 维诺图(Voronoi Diagram)

1.专业术语&#xff08;相关概念&#xff09;&#xff1a; 基点Site&#xff1a;具有一些几何意义的点 细胞Cell&#xff1a;这个Cell中的任何一个点到Cell中基点中的距离都是最近的&#xff0c;离其他Site比离内部Site的距离都要远。 Cell的划分&#xff1a;基点Site与其它的…

Illustrator 2022 for mac (AI 2022中文版)

Illustrator 软件是一种应用于出版、多媒体和在线图像的工业标准矢量插画的软件。作为一款非常好的矢量图形处理工具&#xff0c;该软件主要应用于印刷出版、海报书籍排版、专业插画、多媒体图像处理和互联网页面的制作等&#xff0c;也可以为线稿提供较高的精度和控制&#xf…

Centos7中redis开机自启动设置

以下亲测实践有效。 进入以下目录 cd usr/local/redis/redis-6.2.6/utils/ 编辑修改以下文件内容 vim redis_init_script #修改redis安装启动目录 REDISPORT6379 #修改安装目录 EXEC/usr/local/redis/redis-6.2.6/src/redis-server CLIEXEC/usr/local/redis/redis-6.2.6/sr…

计算机毕业设计 基于Spring Boot智能停车计费系统的设计与实现 Javaweb项目 Java实战项目 前后端分离 文档报告 代码讲解 安装调试

&#x1f34a;作者&#xff1a;计算机编程-吉哥 &#x1f34a;简介&#xff1a;专业从事JavaWeb程序开发&#xff0c;微信小程序开发&#xff0c;定制化项目、 源码、代码讲解、文档撰写、ppt制作。做自己喜欢的事&#xff0c;生活就是快乐的。 &#x1f34a;心愿&#xff1a;点…