本帖最后由 songpeng 于 2021-8-31 17:05 编辑
你好,前台通过在表单页面编辑之后,然后调用后端接口,通过file文件的形式接收,然后加水印之后在返回给前端下载,
但是目前拿到file之后通过输入流返回给前端,打开时报错,
无论加水印还是不加水印都报错。
还有一点,通过file形式,后台解析的数据会有一个隐藏的sheet页,这个是有什么作用?
- public Response<Void> exportExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
- try {
- Subject subject = SecurityUtils.getSubject();
- Principal principal = (Principal) subject.getPrincipal();
- String accountName = principal.getAccountName();
- //获取名称
- String fileName = file.getOriginalFilename();
- //获取输入流
- InputStream inputStream = file.getInputStream();
- //转换成excel
- XSSFWorkbook wb = new XSSFWorkbook(inputStream);
- //水印的内容
- String content = accountName + "-" + LocalDate.now();
- ByteArrayOutputStream byteArrayOutputStream = createWaterMark(content);
- //如果有多个sheet,遍历
- int sheets = wb.getNumberOfSheets();
- for (int i = 0; i < sheets; i++) {
- XSSFSheet sh = wb.getSheetAt(i);
- int pictureIdx = wb.addPicture(byteArrayOutputStream.toByteArray(), Workbook.PICTURE_TYPE_PNG);
- String rId = sh.addRelation(null, XSSFRelation.IMAGES, wb.getAllPictures().get(pictureIdx)).getRelationship().getId();
- sh.getCTWorksheet().addNewPicture().setId(rId);
- }
- //设置相应头
- response.setContentType("application/octet-stream;charset=utf-8");
- response.setCharacterEncoding("utf-8");
- response.setHeader("Content-Disposition", "attachment;filename" + fileName);
- //输出流
- ServletOutputStream os = response.getOutputStream();
- os.flush();
- wb.write(os);
- //关闭流
- os.close();
- wb.close();
- } catch (Exception e) {
- logger.error("导出失败:" + e);
- }
- }
复制代码
|