问题描述
在采用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();
}
}
导出结果