jsp导出word,java导入access,freemarker
1使用jsp+struts导出带有表格的word要点包括:1中文乱码;2以word形式保存文件;3struts标签的基本使用;4<%@ page language="java" pageEncoding="utf-8" %><%@ taglib prefix="s" uri="/struts-tags"%><html><head><%String name =request.getAttribute("name").toString();name = new String(name.getBytes("GBK"),"ISO8859-1")+"";response.setHeader("Content-disposition","attachment; filename="+name+".doc");%></head><body><s:if test="${baseType}==0"><h2 >1.A基本信息</h2><table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0style='width:400pt;font-size:10.0pt;border-collapse:collapse;mso-padding-alt:0cm 0cm 0cm 0cm'> <tr height=30 style='height:22.5pt'> <td style="width:60pt;">姓名</td> <td><s:property value="personInfo.XM"/></td> <td style="width:60pt;">性别</td> <td><s:property value="personInfo.NL"/></td> </tr> </table><h3 >1.2 A扩展信息</h3> <table class=MsoNormalTable border=0 cellspacing=0 cellpadding=0style='width:400pt;font-size:10.0pt;border-collapse:collapse;mso-padding-alt:0cm 0cm 0cm 0cm'> <s:iterator value="personInfo.kzxxList" status="stat"> <tr height=19 style='height:14.25pt'><td style="width:70pt;"><s:property value="typeName" escape="false"/></td><td><s:property value="beanValue" escape="false"/></td> </tr></s:iterator> </table> </s:if> <s:elseif test="${baseType}==1"> <h2 >1.B基本信息</h2> </s:elseif> <h2 >2.关联信息</h2> <s:if test="docList.size()>0"> <h3>文档</h3></s:if></body></html>2 Java将数据导入到Access数据库要点/** * 【业务共享】将指定了Id(由ids决定)的业务数据(由beanType决定)的某些字段(由props决定)导出到access * @param ids 即将导出的数据的id集合。* @param props 导出数据的那些属性 * @param beanName 业务表的bean名称 * @return */private synchronized final int exportData(List<String> ids,String props,String beanType){if(T.isNullList(ids)){return 0;}else{T.print("一共有"+ids.size()+"条数据即将导出");}if(T.isNull(props)){return 0;}//TODO 基础变量String filePath = T.getRealyPath()+"template/bussShare.mdb";String tableName = Constant.BASEINFO_ZZ.equals(beanType)?"表B":Constant.BASEINFO_MZ.equals(beanType)?"表C":"表A";try {//创建jdbc连接。Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Properties prop = new Properties();Connection conn = DriverManager.getConnection("jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+filePath+";", prop);Statement st = conn.createStatement();//TODO 删除旧表try{st.execute("drop table 表A");}catch(Exception e){ }try{st.execute("drop table 表B");}catch(Exception e){ }try{st.execute("drop table 表C");}catch(Exception e){ }//TODO 创建新表。StringBuffer buffer=new StringBuffer(500);buffer.append("create table ").append(tableName).append("(id integer");//主键IDString[] colNames = T.getJSON(props, "before").split(",");for (int i = 0; i < colNames.length; i++) {buffer.append(",").append(colNames).append(" memo ");}buffer.append(" ) ");//TODO carate table最后一个括号。st.execute(buffer.toString());//TODO 创建新表。END//TODO 从gx读取数据,同时写入access数据表中。String[] colArr= T.getJSON(props, "after").split(",");int propSize = colArr.length;//有这么些字段。//TODO 拼凑插入数据的sql模板。StringBuffer insertBaseBuffer=new StringBuffer(500);insertBaseBuffer.append("insert into "+tableName+" values( {id}");for (int i = 0; i < propSize; i++) {insertBaseBuffer.append(",").append("{"+colArr.toLowerCase().trim()+"}");}insertBaseBuffer.append(")");String insertBase = insertBaseBuffer.toString();//TODO 拼凑插入数据的sql模板END//根据模板,生成带有真实数据的sql插入数据String insertsql ;int len = ids.size();PersonInfoLogic personLogic =(PersonInfoLogic) ApplicationContextHolder.getBean("personInfoLogic");Object obj = "";ElecaddressInfo e;OrgInfo o;PersonInfo p;Method[] ms;Method m;String _name;String oValue ;for ( int i=0; i < len; i++) {insertsql =insertBase.replace("{id}", (i+1)+"");p = personLogic.get(ids.get(i)); personLogic.convertDic(p, "view");obj= p;ms = obj.getClass().getMethods();//TODO 所有get方法和set方法的集合。for(int j=0;j<ms.length;j++){if(ms.getName().indexOf("get")>=0){//只要get方法。m = ms;_name = m.getName().replace("get", "").toLowerCase();oValue =T.isNull((m.invoke(obj, null)+""),"").toString();insertsql = insertsql.replace("{"+_name+"}", addChar(oValue));}}st.execute(insertsql);if(i%50==0){T.print(i);}}st.clearBatch();st.close();} catch (Exception e) {e.printStackTrace();}return 0;}3 使用freemarker导出数据/** * 使用freemark导出数据 * @param id 数据ID * @param dataType 数据类型 * @return 生成的物理文件的物理路径 */public static String exportByFreeMark(String baseId,String dataType){PersonInfoLogic personInfoLogic =(PersonInfoLogic) ApplicationContextHolder.getBean("personInfoLogic");try {Configuration cfg=new Configuration();String filePath = WebUtil.getBasePath()+"template";cfg.setDirectoryForTemplateLoading(new File(filePath));cfg.setObjectWrapper(new DefaultObjectWrapper());Template temp=cfg.getTemplate("toword.xml","GBK");Map root=new HashMap();//根List<Map> personlist = new ArrayList<Map>();//关联数据对象root.put("dataType", "person");//数据类型使用dataType做标识PersonInfo instance = personInfoLogic.getViewObj(baseId, null);Map map_person = FreeMarkTool.converPerson(instance);root.put("person",map_person);//对象主题数据String imgPath = WebUtil.getBasePath()+"images/no_image.jpg";root.put("image", T.getFileEncode(imgPath));//图片信息Date currDate=new Date();String name=DateUtil.formatDateTime(currDate, "yyyy-MM-dd")+"_"+currDate.getTime();//文件名String fileUrl = "upload/file/"+name+".doc";File file = new File(T.getRealyPath()+fileUrl);if(file.exists()){file.delete();}FileOutputStream fos = new FileOutputStream(file);Writer out=new OutputStreamWriter(fos,"GBK");temp.process(root, out);out.flush();fos.close();//TODO 必须关闭文件输出流 否则不能删除临时文件。return fileUrl;} catch (Exception e) {e.printStackTrace();}finally{//清空缓存。personInfoLogic.getPersonInfoDAO().getHibSession().clear();}return null;}/** * 将一个数据对象转变成map对象 * @param instance 数据对象 * @return 使用map模拟的数据对象 */public static Map converPerson(PersonInfo instance){String json = "name:{0},age:{1}";Object[] params = new Object;params = T.isNullHTML(instance.getName(),"--");params = T.isNullHTML(instance.getAge(),"--");json = MessageFormat.format(json, params);Map map = T.getMapFromJSON(json);return map;}3 freemarker标签备注:首先使用word另存为生成xml模板,然后替换内容。<#if dataType=="person">${obj.Name}<#list kzxxList as kzxx_item>${kzxx_item.typeName}</#list><#elseif dataType=="orginfo"><#else><w:p><w:r><w:t>无</w:t></w:r></w:p></#if><#if personlist?size gt 0 ></#if>
页:
[1]