关于java导出word模板问题,使用jquery.wordexport.js前端的导出word保留不了原本的word格式,使用后端导出需要将word模板另存为xml,再将名字转换成ftl格式
@RequestMapping("/exportWord")
public void exportWord(HttpServletRequest request, HttpServletResponse response){
String workSheet = request.getParameter("workSheetCode");
Map<String, Object> map = new HashMap<String, Object>();
map.put("workSheetCode", workSheetCodeQuery);
BizflowElectricalTwo bizflow = bWService.getbizflow(map);//获取数据
taskMap.put("bizflow", bizflow);
String path = request.getSession().getServletContext().getRealPath("/")+"/template";//根目录
String fileName = "下载" + bizflowWorkSheet.getWorkSheetCode()+ ".doc"; /下载名称
String tempName = "模板.ftl"; //模板名称
DocUtil.downLoad(request, response, taskMap, path, fileName, tempName);
}
public static void download(HttpServletRequest request,
HttpServletResponse response, String fileUrl, String fileName) {
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
try {
fileUrl = fileUrl + fileName;
response.setContentType("multipart/form-data");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
bis = new java.io.BufferedInputStream(new java.io.FileInputStream((fileUrl)));
bos = new java.io.BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
int i = 0;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
i++;
}
bos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bis = null;
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bos = null;
}
}
}
public static void downLoad(HttpServletRequest request, HttpServletResponse response, Map<String, Object> dataMap, String path, String FileName, String tempName)
{
Writer out = null;
File outFile = null;
try
{
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("utf-8");
configuration.setDirectoryForTemplateLoading(new File(path));
// 输出文档路径及名称
outFile = new File(path + File.separator + FileName);
//以utf-8的编码读取ftl文件
Template t = configuration.getTemplate(tempName,"utf-8");
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"),10240);
t.process(dataMap, out);
download(request, response, outPath + File.separator, FileName);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
finally
{
try
{
if (null != out)
{
out.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
if (outFile.exists())
{
outFile.delete();
}
}
}
ftl模板直接引用编辑后,保存ftl模板,可能会出现乱码问题,删掉中间没用部分即可