http://wenku.baidu.com/link?url=YxTZWVP3ssO-e_Br3LIZVq2xOQnqaSz8gLPiRUDN8NIR_wX2-Z25OqwbVn5kXqGiOFYUMBsaMlWcbHld565N5ENMBTrUOp_-rsrsjIMBlgi
1 public class WordUtil { 2 private Configuration configuration=null; 3 4 public WordUtil () { 5 configuration = new Configuration(); 6 configuration.setDefaultEncoding("utf-8"); 7 } 8 9 public void createDoc(HttpServletRequest request) { 10 //要填入模板的数据文件 11 Map dataMap=new HashMap(); 12 get(dataMap); 13 14 configuration.setServletContextForTemplateLoading(request.getServletContext(), "/WEB-INF/freemarker"); 15 try { 16 Template t=configuration.getTemplate("paperTemplate.flt"); 17 t.setEncoding("UTF-8"); 18 //D:\workspace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Ztree\WEB-INF\freemarker\exam.doc 19 String path=request.getSession().getServletContext().getRealPath("/WEB-INF/freemarker/exam.doc"); 20 Writer out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8")); 21 t.process(dataMap, out); 22 out.close(); 23 24 } catch (TemplateNotFoundException e) { 25 e.printStackTrace(); 26 } catch (MalformedTemplateNameException e) { 27 e.printStackTrace(); 28 } catch (ParseException e) { 29 e.printStackTrace(); 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } catch (TemplateException e) { 33 // TODO 自动生成的 catch 块 34 e.printStackTrace(); 35 } 36 } 37 38 //注意dataMap里存放的数据Key值要与模板中的参数相对应 39 private void get(Map dataMap) { 40 dataMap.put("title", "java笔试试卷"); 41 List<Map<String, Object>> namelist=new ArrayList<Map<String,Object>>(); 42 for (int i = 0; i < 5; i++) { 43 Map<String, Object> map=new HashMap<String, Object>(); 44 map.put("xz1", i+1); 45 map.put("xz2", "下面哪些是Thread类的方法()"+(i+1)); 46 map.put("ans1", "A start()"); 47 map.put("ans2", " B run()"); 48 map.put("ans3", "C exit()"); 49 map.put("ans4", "D getPriority()"); 50 namelist.add(map); 51 } 52 dataMap.put("namelist", namelist); 53 }
时间: 2024-10-03 14:23:11