您的位置:首页 > 编程语言 > Java开发

jsp导出word,java导入access,freemarker

2013-05-23 13:41 405 查看
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=0  style='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=0  style='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");//主键ID  
            String[] colNames = T.getJSON(props, "before").split(",");  
            for (int i = 0; i < colNames.length; i++) {  
                buffer.append(",").append(colNames[i]).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[i].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[j].getName().indexOf("get")>=0){//只要get方法。  
                        m = ms[j];  
                        _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[50];  
    params[0] = T.isNullHTML(instance.getName(),"--");  
    params[1] = 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> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java JSP Word freemarker access