【java】poi word模板生成报告后打不开问题
问题:功能已经实现,需求升级后要求模板可以自己上传,然后下载对应报告。把原来的模板稍加改动后,上传下载word打不开。解决:wps改动的原来的模板,用office修改保存就没问题了。原理:不知道。实现代码:public static void getMoBanDoc(HttpServletRequest req, HttpServletResponse response, M...
·
问题:功能已经实现,需求升级后要求模板可以自己上传,然后下载对应报告。把原来的模板稍加改动后,上传下载word打不开。
解决:wps改动的原来的模板,用office修改保存就没问题了。
原理:不知道。
实现代码:
public static void getMoBanDoc(HttpServletRequest req, HttpServletResponse response, Map<String, String> map, String path, String temppath, String filename){
Properties properties = ConfigProperties.getProperties();
String tempFile = properties.getProperty("temp.path");
File dirFile = new File(tempFile);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String realPath = properties.getProperty("doc.path") + path;
try {
InputStream fileInputStream = new FileInputStream(realPath);
// 读取文本内容
HWPFDocument document = new HWPFDocument(fileInputStream);
Range bodyRange = document.getRange();
// 替换内容
for (Map.Entry<String, String> entry : map.entrySet()) {
bodyRange.replaceText("{$" + entry.getKey() + "}", String.valueOf(entry.getValue()));
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write(byteArrayOutputStream);
FileOutputStream outputStream = new FileOutputStream(temppath);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.flush();
byteArrayOutputStream.close();
outputStream.close();
File file = new File(temppath);
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
response.setContentType("application/msword");
response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(file.length()));
//读取目标文件
InputStream in = new FileInputStream(file);
//通过response将目标文件写到客户端
OutputStream out = response.getOutputStream();
// 写文件
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
out.flush();
in.close();
out.close();
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
更多推荐
所有评论(0)