Apache Poi导出docx文件

问题描述

在采用Hutool中的Word07Writer类导出docx时遇到了:getOutputStream() has already been called for this response 异常
在这里插入图片描述


原因分析:

   导出同时使用了getOutputStream()和write方法,hutool导出方法flush中使用了write,所有导出总抛出异常
public Word07Writer flush(OutputStream out, boolean isCloseOut) throws IORuntimeException {
        Assert.isFalse(this.isClosed, "WordWriter has been closed!", new Object[0]);

        try {
            this.doc.write(out);
            out.flush();
        } catch (IOException var7) {
            throw new IORuntimeException(var7);
        } finally {
            if (isCloseOut) {
                IoUtil.close(out);
            }

        }

        return this;
    }

解决方案:

通过查看hutool导出类中也是使用Apache Poi 中的XWPFDocument类生成数据,所有直接使用XWPFDocument生成docx文件,以下是完整代码。

public void exportData()  {
		try {
			String title = "导出文件名称";
			//导出docx文档
			XWPFDocument document = new XWPFDocument();
			//标题
			XWPFParagraph paragraph = document.createParagraph();
			paragraph.setAlignment(ParagraphAlignment.CENTER);//文字居中
			XWPFRun run = paragraph.createRun();
			run.setBold(true);//文字加粗
			run.setFontSize(18);//文字大小
			run.setText("标题");
			run.addBreak();//换行
			//内容
			XWPFParagraph paragraph1 = document.createParagraph();
			XWPFRun run1 = paragraph1.createRun();
			run1.setBold(true);
			run1.setFontSize(15);
			run1.setText("第一行");
			run1.setColor("0000FF");//颜色
			run1.addBreak();
			run1.setText("第二行");
			run1.setColor("FF0000");//颜色
			//处理内容含有换行符情况
			XWPFParagraph paragraph3 = document.createParagraph();
			XWPFRun run3 = paragraph3.createRun();
			String[] str = "第三行\n 第四行\n 第五行\n  第六行".split("\n");
			for (String content : str) {
				run3.setFontSize(12);
				run3.setText(content);
				run3.addBreak();
			}

			String filename = title + ".docx";
			getHttpResponse().setContentType("application/msword");
			getHttpResponse().setHeader("Content-Disposition", "attachment; filename="
					+ new String((filename).getBytes("utf-8"), "ISO-8859-1") );
			getHttpResponse().addHeader("Cache-Control", "no-cache");
			ServletOutputStream out = getHttpResponse().getOutputStream();
			document.write(out);
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

导出结果
在这里插入图片描述

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值