文件打包下载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导入模板配置导出配置

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

java 复制代码
package com.wenzheng.whsj.prj.export;

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

import java.util.List;
import java.util.Map;

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

	@Autowired
	private PmPrjConcentrateArgumentService pmPrjConcentrateArgumentService;


	@Override
	public List<Map<String, Object>> findData(Map<String, Object> param) {
		LoginUser user = 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);
		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编写替换数据代码

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



@Override
    public ResponseEntity<byte[]> downloadWordReport(HttpServletRequest request, String id, Map<String, Object> params, LoginUser user) throws Exception {
        if (BaseUtils.isNull(id)) {
            return null;
        }
        if (org.apache.commons.collections4.MapUtils.isEmpty(params)) {
            params = 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());
        if (lstTemplate == null || lstTemplate.isEmpty()) {
            throw new TemplateSetException("模板没定义");
        }
        PmTemplateAffix affixTemp = lstTemplate.get(0);
        byte[] data = affixTemp.getFileData();
        //查询数据
        Map<String, Object> map = pmPrjMeasurementReferenceDao.selectById(id);
        if (map == null) {
            throw 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 = new HttpHeaders();
        // 处理文件名编码问题
        String userAgent = request.getHeader("user-agent");
        if (HttpUtils.isMSBrowser(userAgent)) {
            // 如果是IE浏览器,则用URLEncode解析
            fileName = URLEncoder.encode(fileName, "UTF-8");
            fileName = fileName.replace("+", " ");
        } else {
            // 如果是谷歌、火狐则解析为ISO-8859-1
            fileName = new String(fileName.getBytes("gbk"), StandardCharsets.ISO_8859_1);
        }
        headers.set("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<>(data, headers, HttpStatus.OK);
    }



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

        File templateAffixFile = null;
        try {
            templateAffixFile = FileTool.fileToBytes(data, uploadPath + "/" + useObject + "/" + dateStr + "/", "/" + uuidName);
        } catch (Exception e) {
            System.err.println("===========>" + e.getMessage());
        }
        MultipartFile multipartFile = FileTool.getMultipartFile(templateAffixFile);
        PmBaseAffix affix = new PmBaseAffix();
        affix.setAffixId(UUID.randomUUID().toString());
        if (map.get("affix_id") != null) {
            affix.setPrjId(map.get("affix_id").toString());
        } 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(new Date());
        List<PmBaseAffix> pmBaseAffix = pmPrjMeasurementReferenceDao.selectByPrjCode(affix.getPrjId(), useObject);
        if (pmBaseAffix.size() == 0) {
            affixMapper.insert(affix);
        } else {
            affix.setAffixId(pmBaseAffix.get(0).getAffixId());
            affixMapper.updateByPrimaryKeySelective(affix);
        }
        return affix.getAffixId();
    }

用到的工具方法

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

	public static  MultipartFile getMultipartFile(File file) {
		FileInputStream fileInputStream = null;
		MultipartFile multipartFile = null;
		try {
			fileInputStream = new FileInputStream(file);
			multipartFile = new MockMultipartFile(file.getName(), file.getName(),
					ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return multipartFile;
	}
相关推荐
AI导出鸭PC端4 小时前
文心怎样生成word文档?一键智能排版,AI导出鸭解决格式错乱痛点
人工智能·ai·word·豆包·deepseek·ai导出鸭
AI英德西牛仔19 小时前
从Excel乱象到批量交付:秘塔Excel与“AI导出鸭”PC版的底层重构逻辑
人工智能·重构·excel·deepseek·ai导出鸭
上海魁鲸科技有限公司20 小时前
APS高级排产系统到底有什么用?一文讲清功能、选型与落地建议
前端·microsoft·excel
AI导出鸭1 天前
怎么让文心做表格?AI导出鸭苹果版将文心输出的管道表格智能解析为二维结构,一键导出为Excel或Word标准表格
人工智能·chatgpt·word·excel·ai导出鸭
admin0052 天前
Excel记账和财务软件记账哪个好?效率与准确率真实对比
excel·excel记账·财务软件记账·小微企业记账
wujian83112 天前
AI手机版怎么直接生成word?用“AI 导出鸭”把碎片时间变成专业文档
人工智能·ai·chatgpt·智能手机·word·ai导出鸭
鲲穹AI种草2 天前
多文档批量整理如何选?多款 Word 处理工具能力客观记录
word·文档处理
Python私教2 天前
Excel 和群聊什么时候该升级成管理系统?7 个判断信号
excel·管理系统·权限设计
鲲穹AI种草2 天前
表格数据处理怎么选?多款 Excel 工具能力客观记录
excel·表格数据处理
AI英德西牛仔2 天前
Claude导出word指令的PC端最优解:AI导出鸭电脑版底层逻辑全拆解
人工智能·word·excel·deepseek·ai导出鸭