欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java操作Jxl实现数据交互。三部曲——《第三篇》

程序员文章站 2022-07-04 22:32:38
Java操作Jxl实现上传文本文件实现转PDF格式在线预览。 本文实现背景Web项目:前台用的框架是Easyui+Bootstrap结合使用,需要引入相应的Js、Css文件。页面:Jsp、拦截请求:Servlet、逻辑处理:ClassBean、数据库:SQLserver。 注意:Bean中操作SQL ......

java操作jxl实现上传文本文件实现转pdf格式在线预览。

本文实现背景web项目:前台用的框架是easyui+bootstrap结合使用,需要引入相应的js、css文件页面:jsp、拦截请求:servlet、逻辑处理:classbean、数据库:sqlserver

注意:bean中操作sql语句进行处理是公司内部方法,可替换为其它方法自行扩展!主要看代码逻辑业务处理!

首先我们看见的是easyui中的datagrid中的数网格。

Java操作Jxl实现数据交互。三部曲——《第三篇》

 

接下来进行创建一个xsl文本格式数据文件

Java操作Jxl实现数据交互。三部曲——《第三篇》

 

 

 

 

我们任意点击条数据,点击附件这是弹出一个窗口让我们进行附件上传,只能上传文本数据格式!

Java操作Jxl实现数据交互。三部曲——《第三篇》

 

 点击保存附件上传成功!该附件信息文件名称及文件路径以保存在数据库中,查询该人员的相关信息及附件信息,此时此刻可查看附件信息

Java操作Jxl实现数据交互。三部曲——《第三篇》

 

 点击查看及可把xls数据格式在线转码为pdf格式数据进行展示!(注:在线转码与预览需要一些本地配置,请关注我下一篇博客!)

Java操作Jxl实现数据交互。三部曲——《第三篇》

jsp代码:

<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<%@page language="java" contenttype="text/html; charset=utf-8" pageencoding="utf-8"%>
<%@ page import="com.pantech.base.common.tools.mytools"%>
<%@ page import="com.pantech.base.common.tools.publictools"%>
<%@ page import="com.pantech.src.develop.logs.*"%>
<%@ page import="com.pantech.base.common.tools.*"%>
<%@ page import="com.pantech.src.develop.store.user.*"%>
<%@ page import="com.pantech.src.develop.manage.workremind.workremind"%>
<%@ page import="java.util.vector"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.pantech.base.common.db.dbsource"%>

<html>
<head>


    
    <title>导入文件转为fdf格式在线预览</title>
    <link rel="stylesheet" type="text/css" href="<%=request.getcontextpath()%>/css/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="<%=request.getcontextpath()%>/css/themes/default/easyui.css">
    <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/bootstrap.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/naber.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/font-awesome/css/font-awesome.css">
    <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/sms-index.css"/>
    <link charset="utf-8" rel="stylesheet" href="<%=request.getcontextpath()%>/css/listpage.css"/>
    <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/jquery.min.js"></script>
    <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="<%=request.getcontextpath()%>/script/jqueryui/locale/easyui-lang-zh_cn.js"></script>
    <script charset="utf-8" src="<%=request.getcontextpath()%>/script/bootstrap.min.js"></script>
    <script charset="utf-8" src="<%=request.getcontextpath()%>/script/layer/layer.js"></script>
    <script type="text/javascript" src="<%=request.getcontextpath()%>/script/common/clientscript.js"></script> 
    <script type="text/javascript" src="<%=request.getcontextpath()%>/script/common/publicscript.js"></script>
        <script type="text/javascript" src="<%=request.getcontextpath()%>/script/ajaxfileupload.js"></script>
        <script type="text/javascript" src="<%=request.getcontextpath()%>/script/common/publicscript.js"></script>
        <script type="text/javascript" src="<%=request.getcontextpath()%>/script/flexpaper/flexpaper_handlers.js"></script>
          <script type="text/javascript" src="<%=request.getcontextpath()%>/script/flexpaper/flexpaper.js"></script>
        <style type="text/css">
            #divpagemask2{background-color:#d2e0f2; filter:alpha(opacity=90);left:0px;top:0px;z-index:100;}
            #divpagemask3{background-color:#d2e0f2; filter:alpha(opacity=90);left:0px;top:0px;z-index:100;}
            #win td{height:30px;}
        </style>
    </head>
<body class="easyui-layout" >
    <!-- 页面学生列表区 -->
    <div id="tablediv" class="list-table table-responsive" style="height:600px;width: 900px">
        <table id="list" width="100%"></table>
    </div>

    <!-- 上传附件弹窗 -->
    <div id=jxdialog style="overflow: hidden;">
        <div id="north" region="north" title="教学管理">
            <table id="tb">
                <tr>
                    <td><a href="#" id="newfjsc" class="easyui-linkbutton"plain="true" iconcls="icon-new" onclick="dotoolbar(this.id);"title="">上传附件</a></td>
                    <td><a href="#" id="delfjxx" class="easyui-linkbutton"plain="true" iconcls="icon-cancel" onclick="dotoolbar(this.id);"title="">删除</a></td>
                </tr>
            </table>
        </div>
        <div region="center">
            <table id="jxbzlist"></table>
        </div>
    </div>


    <!-- 附件上传 -->
    <div id="jxbzinfo" style="overflow:hidden;">
        <form id="form1" method='post'>
            <table style="width:100%;" class="tablestyle">
                <tr>
                    <td class="titlestyle">附件上传</td>
                    <td>
                        <input type="file" name="file1" id="icjxbz_upload" style="width:280px;" />
                    </td>
                </tr>
            </table>
            <div style="display: none;">
                <input type="hidden" id="active" name="active"/>
            </div> 
        </form>
    </div>


    <!-- 遮罩层 -->
    <div id="ic_flexpaperzhezhao" style="position:absolute; z-index:99999; width:100%; height:100%; background-image:url('<%=request.getcontextpath()%>/images/course/pic5.png'); display:none;  text-align:center;" onclick="$('#ic_flexpaperdiv').hide();">
            <font color="white" style="position:relative; top:45%; left:0;">文件预览加载中<br/><img src="<%=request.getcontextpath()%>/images/course/loading.gif" /></font>
    </div>
            
    <!-- 文件预览 flexpaper -->
    <div id="ic_flexpaperdiv" style="position:absolute; z-index:99999; width:100%; height:100%; background-image:url('<%=request.getcontextpath()%>/images/course/pic5.png'); display:none;" onclick="$('#ic_flexpaperdiv').hide();">
        <div id="documentviewer" class="flexpaper_viewer" style="width:90%;height:90%; position:relative; top:5%; left:5%;">
        </div>
    </div>        
        
</body>
<script type="text/javascript">
    var xsbh='';
    var uploadpath='<%=mytools.getprop(request, "base.jywdstandarduploadpath")%>';//上传路径
    var filepreview='<%=mytools.getprop(request, "base.jywdstandardfilepreview")%>';//预览路径
    var iusercode="<%=mytools.getsessionusercode(request)%>";   //获得用户登录code    

    $(document).ready(function(){
        loadgrid();
        loaddialog();
    });
    
    
    //dialog窗口
    function loaddialog() {
        //上传附件弹窗
        $('#jxbzinfo').dialog({   
            width: 480,//宽度设置   
            height: 120,//高度设置 
            modal:true,
            closed: true,   
            cache: false, 
            draggable:false,//是否可移动dialog框设置
            toolbar:[{
                //保存编辑
                text:'保存',
                iconcls:'icon-save',
                handler:function(){
                    //传入save值进入dotoolbar方法,用于保存
                    dotoolbar('savefjxx');
                }
            }],
            //打开事件
            onopen:function(data){},
            //读取事件
            onload:function(data){},
            //关闭事件
            onclose:function(data){
                //上传附件表单元素数据
                var file = $('#icjxbz_upload');
                file.after(file.clone().val(""));
                file.remove(); 
                jxloadgrid(maindata[0].学生编号);  //调用读取附件页面信息
                
            }
        });
        
        //上传教学附件
        $('#jxdialog').dialog({   
            width: 800,//宽度设置   
            title:'教学管理计划',
            height: 480,//高度设置 
            modal:true,
            closed: true,  
            cache: false, 
            draggable:false,//是否可移动dialog框设置
            //打开事件
            onopen:function(data){},
            //读取事件
            onload:function(data){},
            //关闭事件
            onclose:function(data){
                ikeycode=xsbh;                
            }
        });
        
    }


    //上传附件信息    
    function jxloadgrid(zy) {
        xsbh=zy;
        loadgridfjsc(zy);
        $('#jxdialog').dialog('open');
    }



    //工具按钮
    function dotoolbar(itoolbar){
        //判断获取参数为new,执行新建附件操作
        if(itoolbar == 'newfjsc'){
            $('#jxbzinfo').dialog('settitle', '新建教学附件信息');
            $('#jxbzinfo').dialog('open');        //打开dialog
        }
    
        //执行保存附件信息操作
        if(itoolbar == 'savefjxx'){ 
            if($('#icjxbz_upload').val()==''){
                alertmsg("请选择上传文件");
                return;
            }
        
            var filetypephoto='<%=mytools.getprop(request, "[filetypephoto]")%>';  //图片
            var filetypetxt='<%=mytools.getprop(request, "[filetypetxt]")%>';    //文本
            var filesuffix=$("#icjxbz_upload").val().split('.')[$("#icjxbz_upload").val().split('.').length-1]; //获取文件后缀名
        
             if (filetypetxt.indexof(filesuffix)!=-1) {
                checkfile();//新建
            }else {
                alertmsg("只能上传文本格式的文件");
                return;
            }
            
        }

        //删除附件信息操作
        if(itoolbar=="delfjxx"){
            if(ikeycode==""){
                alertmsg("请先选择一行数据");
                return;
             }
             confirmmsg("删除后,将无法恢复,是否继续?","delrec();","");
        }
        
        
    }

    
    //删除附件信息方法
    function delrec(){
        $.ajax({
        type:'post',
        url:"<%=request.getcontextpath()%>/importtextbean_servlet",
        data:"active=deleterow&fjxxbh=" + ikeycode,
        datatype:'json',
            success:function(datas){
                if(datas[0].msg=="删除成功"){
                    showmsg(datas[0].msg);
                     jxloadgrid(xsbh);  //调用读取附件页面信息
                }
                
            }
        });   
    }



//加载datagrid主页面信息
function loadgrid(){
    $('#list').datagrid({
        url: '<%=request.getcontextpath()%>/importtextbean_servlet',
        queryparams: {"active":"loadelective"},
        loadmsg : "信息加载中请稍后!",//载入时信息
        nowrap: false,//当数据长度超出列宽时将会自动截取
        showfooter:true,
        rownumbers: true,
        animate:true,
        striped : true,//隔行变色
        pagesize : 10,//每页记录数
        singleselect : true,//单选模式
        pagenumber : 20,//当前页码
        pagination:true,
        fit:true,
        fitcolumns: true,//设置边距
        columns:[[
            {field:'姓名',title:'姓名',width:fillsize(0.2)},
            {field:'所在区域',title:'所在区域',width:fillsize(0.2)},
            {field:'col3',title:'附件',width:fillsize(0.1),
                formatter:function(value,rec,index){
                    return "<input type='button' style='cursor:pointer;' value='[附件]' onclick='jxloadgrid(\""+rec.编号+"\");'>&nbsp;"; 
            }}
        ]],
        onclickrow:function(rowindex, rowdata){
            row=rowdata;
        },
        onloadsuccess: function(data){
            ikeycode='';
        },
        onloaderror:function(none){
            
        }
    });
    

}





/* 学生个人附件信息列表数据 */
function loadgridfjsc(zy){
    $('#jxbzlist').datagrid({
        url:'<%=request.getcontextpath()%>/importtextbean_servlet',
        queryparams:{"active":"querylist","xsbh" : zy}, 
        loadmsg : "信息加载中请稍侯!", //载入时信息
        title:'教学计划信息列表',
        width : '785px', //宽度       
        height : '500px',
        nowrap : false, //截取当数据长度超出列宽时会自动截取
        fitcolumns : true, //自适应列宽防止出现水平滚动
        striped : true, //隔行变色
        pagination : true, //分页
        showfooter:true, //显示页脚信息
        pagesize : 10, //每页记录数
        singleselect : true, //单选模式 这里是指只能选一行不能多选
        pagenumber :1, //当前页码
        rownumbers:true,
        columns:[[
            //field为读取数据的数据名,title为显示的数据名,width宽度设置,align数字在表格中显示的位置
            {field:'编号',title:'教学计划编号',hidden:true},
            {field:'文件名',title:'文件名称',width:fillsize(0.12),align:'center'},
            {field:'创建人',title:'上传人',width:fillsize(0.15),align:'center'},
            {field:'创建时间',title:'上传时间',width:fillsize(0.15),align:'center'},
            {field:'col3',title:'附件',width:fillsize(0.15),align:'center',
                formatter:function(value,rec,index){
                    return "<input type='button' style='cursor:pointer;' value='[查看]' onclick='decidefile(\""+rec.文件路径+"\",\""+rec.预览路径+"\",\""+index+"\");'>" 
            }}
        ]],
        //单击某行时触发
        onclickrow:function(rowindex,rowdata){
            //主键赋值
            ikeycode = rowdata.编号;
            currowdata = rowdata;
        },
        //加载成功后触发
        onloadsuccess: function(data){
            ikeycode = '';
            currowdata = '';
            maindata=data;
        }
        
    });
};

    
    
    /**检查上传文件*/
    function checkfile(){
        var filepath = $("#icjxbz_upload").val();
       
        var pattern = /^[^\s]*$/;
        var fname = filepath.substring(filepath.lastindexof("\\")+1, filepath.length);
        if(!pattern.test(fname)){//匹配文件名
            alertmsg('文件名中不能有空格!',0);
            return;
        }
        
        var arr = filepath.split('\\');
        var filename = arr[arr.length-1];
        if(filepath!=""){
            uploadfile('icjxbz_upload');
        } 
    }
        
    
    //上传附件请求方法
    function uploadfile(fileid){
            $.ajaxfileupload({
                url:'<%=request.getcontextpath()%>/importtextbean_servlet?active=uploadify&xsbh='+xsbh, //服务器地址
                secureuri:false,
                /*type:"post", */
                fileelementid:fileid,//文件选择框的id属性
                datatype: 'text',//服务器返回的格式,可以是json
                success: function (data){//相当于java中try语句块的用法
                    if(data == '上传文件成功'){
                        //提示信息
                        showmsg('上传文件成功');
                        loadgridfjsc(xsbh);
                        $('#jxbzinfo').dialog('close');
                    }else{
                        $('#jxbzinfo').dialog('close'); 
                        loadgridfjsc(jxskjhmx_bh);
                        alertmsg(data);
                    }
                    
                }
           }); 
       }
                
        
        

    //预览的是图片还是文本进行处理
    function decidefile(path, previewpath,index){
        currowdata=maindata.rows[index];
        preview(path, previewpath);//文本
    }
         

    //显示文本文件预览
    function preview(path, previewpath){
        $('#ic_flexpaperzhezhao').show();
        var swfpath =filepreview+previewpath;
        $.ajax({
           type: 'post',
           url: '<%=request.getcontextpath()%>/importtextbean_servlet',   
           data: 'active=filetoswf&filepath='+path, 
           //datatype: 'json',    
           success: function(datas){
                if(datas != '') {
                       var json = eval("("+datas+")");
                       //判断文件是否转换成功
                       if(json[0].msg == '转换成功'){ 
                           $('#documentviewer').flexpaperviewer({
                               config : {
                                   //需要使用flexpaper打开的文档
                                swffile : escape(swfpath), 
                                //初始化缩放比例
                                scale : 1.0,    
                                //缩放样式,其他可选值包括:easenone,easeout,linear,easeoutquad
                                zoomtransition : 'easeout',  
                                //从一个缩放比例变为另外一个缩放比例需要花费的时间,该参数值应该为0或更大
                                zoomtime : 0.5,  
                                //缩放比例之间间隔
                                zoominterval : 0.2, 
                                //初始化时自适应页面
                                fitpageonload : false,
                                 //初始化时自适应页面宽度  
                                fitwidthonload : false, 
                                 //当设置为true时,单击全屏按钮会打开一个flexpaper最大化的新窗口而不是全屏,当由于flash播放器因为安全而禁止全屏,而使用flexpaper作为独立的flash播放器的时候设置为true是个优先选择
                                fullscreenasmaxwindow : false,
                                //当设置为true时,展示文档时不会加载完整个文档,而是逐步加载,但是需要将文档中转化为9以上的版本(使用pdf2swf的时候使用-t 9标签)
                                progressiveloading : false, 
                                //设置最小的缩放比例
                                minzoomsize : 0.5,  
                                //设置最大的缩放比例        
                                maxzoomsize : 3,            
                                //设置为true时,单击搜索所有符合条件的地方高亮显示
                                searchmatchall : false,    
                                //设置启动模式如“portrait”或“towpage” 
                                initviewmode : 'portrait',  
                                renderingorder : 'flash',
                                startatpage : '',
                                //工具栏上是否显示样式选择框
                                viewmodetoolsvisible : true, 
                                //工具栏上时候显示缩放工具
                                zoomtoolsvisible : true,  
                                //工具栏上是否显示导航工具   
                                navtoolsvisible : true,  
                                //工具栏上是否显示光标工具    
                                cursortoolsvisible : true,   
                                //工具栏上是否显示搜索工具
                                searchtoolsvisible : false,  
                                wmode : 'window',
                                //设置地区(语言)
                                localechain: 'zh_cn'  
                            }
                           });
                           
                        $('#ic_flexpaperzhezhao').hide();
                        $('#ic_flexpaperdiv').show();
                       }else if(json[0].msg == '转换失败'){
                           //判断servermsg值
                           if(json[0].servermsg == 'openoffice服务未启动'){
                               alertmsg('openoffice服务已重新启动,点击确定后可重新预览!');
                           }else if(json[0].servermsg == 'openofficebat文件不存在'){
                               alertmsg('openoffice服务启动文件不存在,如有疑问请联系管理员!');
                           }else{
                               alertmsg('文件暂时无法预览,如有疑问请联系管理员!');
                           }
                           $('#ic_flexpaperzhezhao').hide();
                       }
                   }
            }
        });            
    }

</script>
</html>

servlet代码:

package or.og.jxldemo;

import java.io.ioexception;
import java.net.urldecoder;
import java.sql.sqlexception;
import java.util.vector;

import javax.servlet.servletexception;
import javax.servlet.http.httpservlet;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;

import com.pantech.base.common.exception.wrongsqlexception;
import com.pantech.base.common.tools.jsonutil;
import com.pantech.base.common.tools.mytools;
import com.pantech.base.common.tools.tracelog;

import net.sf.json.jsonarray;

/**
 * servlet implementation class importtextbean_servlet
 */
public class importtextbean_servlet extends httpservlet {

    protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        dopost(request, response);
    }

    protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
        //设置字符编码为utf-8
        request.setcharacterencoding("utf-8");
        response.setcontenttype("text/html;charset=utf-8");
        
        string active = mytools.strfiltr(request.getparameter("active"));// 拿取前台的active值
        int pagenum = mytools.parseint(request.getparameter("page"));    //获得页面page参数 分页
        int pagesize = mytools.parseint(request.getparameter("rows"));    //获得页面rows参数 分页
        
        vector jsonv = null;//返回结果集
        jsonarray jal = null;//返回json对象
        importtextbean bean = new importtextbean(request);
        this.getformdata(request, bean); //获取submit提交时的参数(ajax适用)
        system.out.println("active:--"+active);

        
        
        //读取学生信息
        if("loadelective".equalsignorecase(active)){  
            try {
                jsonv = bean.loadelective(pagenum, pagesize);
                
                jal = (jsonarray)jsonv.get(2);
                response.getwriter().write("{\"total\":" + mytools.strfiltr(jsonv.get(0)) + ",\"rows\":" + jal.tostring() + "}");//返回前台datagrid需要的数据格式
                tracelog.trace("{\"total\":" + mytools.strfiltr(jsonv.get(0)) + ",\"rows\":" + jal.tostring() + "}");
            } catch (sqlexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
        }
    
        
        //查询附件信息表
        if("querylist".equalsignorecase(active)) {
            string xsbh =mytools.strfiltr(request.getparameter("xsbh")); //学生编号
            try {
                jsonv = bean.querylist(xsbh);
                jal = (jsonarray)jsonv.get(2);//转化为json数据格式
                response.getwriter().write(jal.tostring());//返回数据到前台
            } catch (sqlexception e) {
                // todo auto-generated catch block
                e.printstacktrace();
            }
        }
        
        
        
        
        //上传附件请求方法
        if("uploadify".equalsignorecase(active)){
            string xsbh =mytools.strfiltr(request.getparameter("xsbh")); //学生编号
            string savepath = "";
            savepath=mytools.getprop(request, "base.jywdstandarduploadpath");
            string savetestpath = mytools.getprop(request, "base.testpathfile");
    
            system.out.println("--上传路径:"+savepath+"--文档类型:");
            diskfileitemfactory fac = new diskfileitemfactory();  
            servletfileupload upload = new servletfileupload(fac);  
            upload.setheaderencoding("utf-8");  
               
            bean.uploadifyfile(savepath, request, response); //调用创建文件方法
            if (bean.getmsg().equals("保存成功")) {
                try {
                    bean.uploadtodb(request,xsbh);
                } catch (sqlexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                } catch (wrongsqlexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }    //调用插入数据方法
                response.getwriter().write(bean.getmsg());
            }else {
                response.getwriter().write(bean.getmsg());
            }
        }
        
        
        
        
        //将word等文件转换成swf格式
        if("filetoswf".equalsignorecase(active)){ 
            string path = mytools.strfiltr(request.getparameter("filepath"));  //文件路径
            string filepath =path;
            office2swf o2s = new office2swf(request, filepath);
            boolean flag = o2s.conver();
            
            if(flag){
                jal = jsonutil.addjsonparams(jal,"msg", "转换成功");
            }else{
                jal = jsonutil.addjsonparams(jal,"msg", "转换失败");
                if("openoffice服务未启动".equalsignorecase(o2s.getmsg()) || "openofficebat文件不存在".equalsignorecase(o2s.getmsg())){
                    jal = jsonutil.addjsonparams(jal, "servermsg", o2s.getmsg());
                }
            }
            response.getwriter().write(jal.tostring());
        }
        
        
        
        //删除附件信息表
        if("deleterow".equalsignorecase(active)) {
            string fjxxbh = mytools.strfiltr(request.getparameter("fjxxbh"));  //附件信息编号
            
            try {
                //调用删除操作
                bean.deleterow(fjxxbh);
                //返回操作信息
                jal=jsonutil.addjsonparams(jal, "msg", bean.getmsg());
                response.getwriter().write(jal.tostring());
            } catch (sqlexception e) {
                e.printstacktrace();
                jal = jsonutil.addjsonparams(jal, "msg", "无法获取数据<br>"+bean.getmsg());
                response.getwriter().write(jal.tostring());
            } catch (wrongsqlexception e) {
                e.printstacktrace();
            }         
        }
        
        
        
    }
    
    
    
    /**
    * 从界面没获取参数
    * @date 
    * @author:yeq
    * @param request
    * @param majorsetbean
    */
    private void getformdata(httpservletrequest request, importtextbean bean){
        bean.setusercode(mytools.getsessionusercode(request));   //usercode
    }
    

}

bean代码:

package or.og.jxldemo;

import java.io.bufferedinputstream;
import java.io.bufferedwriter;
import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.outputstreamwriter;
import java.sql.sqlexception;
import java.text.simpledateformat;
import java.util.date;
import java.util.iterator;
import java.util.list;
import java.util.vector;

import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;

import com.pantech.base.common.db.dbsource;
import com.pantech.base.common.exception.wrongsqlexception;
import com.pantech.base.common.tools.mytools;

public class importtextbean {
    

    private httpservletrequest request;
    private string usercode;//用户编号
    private dbsource db;
    
    
    private string    gx_fjxxbh;//附件信息编号
    private string    gx_fjxxwjm;//附件信息文件名
    private string    gx_fjxxtypt;//附件信息文件类型
    private string    gx_fjxxwjlj;//附件信息文件路径
    private string    gx_fjxxyllj;//附件信息预览路径
    private string msg;  //提示信息
    /**
     * 构造函数
     * @param request
     */
    public importtextbean(httpservletrequest request) {
        this.request = request;
        this.db = new dbsource(request);
    }
    
    
    
    //读取学生信息
    public vector loadelective(int pagenum,int pagesize) throws sqlexception {
        dbsource dbsource = new dbsource(request);
        vector vector = null;
        string sql = "";
        
        sql="select * from [student].[dbo].[v_基础信息_学生信息表] ";
        vector = dbsource.getconttexjonsarr(sql, pagenum, pagesize);
        return vector;
    }
    
    
    
    //查询附件信息表
    public vector querylist(string xsbh) throws sqlexception {
        string sql="";
        vector vec = null; // 结果集
        sql="select [编号],[学生编号],[文件名],[文件类型],[文件路径],[预览路径],[创建人],convert(nvarchar(19),创建时间,21) as 创建时间,[状态]   " + 
            "from [v_学生管理_附件信息表]  where 学生编号 ='" + mytools.fixsql(xsbh)+"'";
        vec = db.getconttexjonsarr(sql, 0, 0);
        return vec;
    }
    
    
    
    
    
    
    
    //uploadify上传文件
    public void uploadifyfile(string savepath, httpservletrequest request, httpservletresponse response){
        file f1 = new file(savepath);  
        //当文件夹不存在时创建
        if (!f1.exists()) {  
            f1.mkdirs();  
        }  
        diskfileitemfactory fac = new diskfileitemfactory();  
        servletfileupload upload = new servletfileupload(fac);  
        upload.setheaderencoding("utf-8");  
        list filelist = null;  
        try {  
            filelist = upload.parserequest(request);  
            iterator<fileitem> it = filelist.iterator();  
         
            string name = "";   //文件名
            string extname = "";  //文件后缀名
            int dian=0;//点所在的位置
            
            while (it.hasnext()) {  
                fileitem item = it.next();  
                if (!item.isformfield()) {  
                    name = item.getname();
                    string filename = name;
                    long size = item.getsize();  
                    string type = item.getcontenttype();  
                    system.out.println(size + " " + type);  
                    if (name == null || name.trim().equals("")) {  
                        continue;  
                    }  
                    //扩展名格式    
                    if (name.lastindexof(".") >= 0) {  
                        extname = name.substring(name.lastindexof("."));  //获取文件格式
                    }  
                    file file = null;
                    string filepath = "";  //文件路径
                    string tempfilepath = ""; //文件临时路径
                    //simpledateformat form = new simpledateformat("hh-mm-ss-ss");
                    long ct =system.currenttimemillis(); //获得当前系统时间毫秒,毫秒数其实就是自1970年1月1日0时起的毫秒数
                    date newdate=new date();//给图片加时间为防止页面图片不刷新
                    //string temp1=form.format(newdate);
                    do {  
                        //生成文件名  
                        //name = temp1.replaceall("-", "").touppercase();
                        name=string.valueof(ct)+"-"+this.getusercode();  //获得毫秒数生成文件名加上当前登入人
                        filepath = savepath +""+ name+extname ;
                        tempfilepath =  name+""+extname;
                        dian=tempfilepath.indexof(".");
                        file = new file(filepath);  
                    } while (file.exists());
                    file savefile = new file(filepath);  
                    item.write(savefile);
                    
                  //判断如果文件是txt文件的话,根据不同编码修改编码为utf-8,以免预览出现乱码
                    if(".txt".equalsignorecase(extname)){
                        string code = judgecharset(new file(filepath));//判断文件编码
                        //system.out.println("++++++++++++++++++++++++++++++上传文件字符集为:"+code);
                        if(!"utf-8".equalsignorecase(code)){
                            bufferedwriter bw = new bufferedwriter(new outputstreamwriter(new fileoutputstream(new file(filepath)),"utf-8")); 
                            bw.write(new string(item.getstring(code).getbytes("utf8"),"utf-8"));
                            bw.flush();
                            bw.close();
                        }
                    }
                    this.setgx_fjxxtypt(extname);  //附件信息文件类型,执行获得附件类型字段方法
                    this.setgx_fjxxwjm(filename);  //文件名
                    this.setgx_fjxxwjlj(filepath);  //文件完整路径
                    this.setgx_fjxxyllj(tempfilepath.substring(0, dian)+".swf"); //文件临时路径
                    system.out.println(extname+":"+filename+"&&"+filepath);
                }
                this.setmsg("保存成功");
            }  
            
        } catch(exception e){
                this.setmsg("保存失败");
            e.printstacktrace();
        }
    }
    
    

    //往数据库插入
    public void uploadtodb(httpservletrequest req, string xsbh) throws sqlexception, wrongsqlexception{
        dbsource db = new dbsource(req);  //声明数据库连接对象
        simpledateformat form = new simpledateformat("hh-mm-ss-ss");
        date newdate=new date();//给图片加时间为防止页面图片不刷新
        string sql="";
            string temp1=form.format(newdate);
            system.err.println("sql:"+temp1);
                   
                sql = "insert into [v_学生管理_附件信息表] ([编号],[学生编号],[文件名],[文件类型],[文件路径],[预览路径],[创建人],[创建时间],[状态]) values ("+
                        "newid(),"+    //编号    
                        "'"+mytools.fixsql(xsbh)+"',"+ //学生编号    
                        "'"+mytools.fixsql(this.getgx_fjxxwjm())+"',"+    //文件名    
                        "'"+mytools.fixsql(this.getgx_fjxxtypt())+"',"+    //文件类型
                        "'"+mytools.fixsql(this.getgx_fjxxwjlj())+"',"+        //文件路径
                        "'"+mytools.fixsql(this.getgx_fjxxyllj())+"',"+        //预览路径
                        "'post',"+                                            //usercode
                        "getdate(),'1'"+                                    //创建时间
                        ")";    
                if(db.executeinsertorupdate(sql)){
                    this.setmsg("上传文件成功");
                }else{
                    this.setmsg("上传文件失败");
                }    
        
    }
    
    
    

    //判断文件编码
    public string judgecharset(file file) {
        string charset = "gbk";
        byte [] first3bytes = new byte[3];
        try {
            boolean checked = false;
            bufferedinputstream bis = new bufferedinputstream(new fileinputstream(file));
            bis.mark(0);
            int read = bis.read(first3bytes, 0, 3);
            if (read == -1) return charset;
            if (first3bytes[0] == (byte)0xff && first3bytes[1] == (byte)0xfe) {
                charset = "utf-16le";
                checked = true;
            }else if(first3bytes[0] == (byte)0xfe && first3bytes[1] == (byte)0xff) {
                charset = "utf-16be";
                checked = true;
            }else if(first3bytes[0] == (byte)0xef && first3bytes[1] == (byte)0xbb && first3bytes[2] == (byte)0xbf) {
                charset = "utf-8";
                checked = true;
            }
            bis.reset();
            
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xf0)
                        break;
                    if (0x80<=read && read <= 0xbf) //单独出现bf以下的,也算是gbk
                        break;
                    if (0xc0<=read && read <= 0xdf) {
                        read = bis.read();
                        if (0x80<= read && read <= 0xbf)//双字节 (0xc0 - 0xdf) (0x80 - 0xbf),也可能在gb编码内
                            continue;
                        else
                            break;
                    } else if (0xe0 <= read && read <= 0xef) {//也有可能出错,但是几率较小
                        read = bis.read();
                    if (0x80<= read && read <= 0xbf) {
                        read = bis.read();
                        if (0x80<= read && read <= 0xbf) {
                            charset = "utf-8";
                            break;
                        } else
                            break;
                    } else
                        break;
                    }
                }
            }
            bis.close();
        } catch (exception e) {
            e.printstacktrace();
        }
        
        return charset;
    }
        
        
        
        
        //删除附件信息表
        public void deleterow(string fjxxbh)throws sqlexception, wrongsqlexception{
            string sql = "";
            vector vec = null;
            
            //查询文件路径
            string filename = "";
            sql = "select [文件路径] from [v_学生管理_附件信息表]  where 编号='" + mytools.fixsql(fjxxbh) + "'";
            vec = db.getcontextvector(sql);
            if(vec.size()>0 && vec!=null)
                filename = mytools.fixsql(mytools.strfiltr(vec.get(0)));
            
            sql = "delete from [v_学生管理_附件信息表] where 编号='" + mytools.fixsql(fjxxbh) + "' ";
            
            if(db.executeinsertorupdate(sql)){
                if(filename.length()>0){
                    //截取文件名
                    filename = filename.substring(filename.lastindexof("/")+1, filename.lastindexof("."));
                    //删除相关文件
                    deletefile(filename);
                }
                
                this.setmsg("删除成功");//成功设置消息为<删除成功>
            }else{
                this.setmsg("删除失败");//失败设置消息为<删除成功>
            }
        }
        
        
        
    //删除相关文件    
    public boolean deletefile(string filename){
        boolean result = true;
        
        //获取配置路径
        string url = mytools.getprop(request, "base.jywdstandarduploadpath");
        //删除该教学标准信息的上传文件及pwf文件
        file folder = new file(url);
        file temp = null;
        file[] filelist = folder.listfiles();//列出文件里所有的文件
        int loc = 0;
        for(int i=0; i<filelist.length; i++){//对这些文件进行循环遍历
            temp = filelist[i];
            loc = temp.getname().indexof(filename);//获取文件名字符的位置
            if(loc!=-1){//去掉后缀,如果文件名为该文件名的话就删除
                temp.delete();//删除文件
            }
        }
        
        return result;
    }
        
    
    
    
    
    
    public string getgx_fjxxbh() {
        return gx_fjxxbh;
    }

    public void setgx_fjxxbh(string gx_fjxxbh) {
        gx_fjxxbh = gx_fjxxbh;
    }

    public string getgx_fjxxwjm() {
        return gx_fjxxwjm;
    }

    public void setgx_fjxxwjm(string gx_fjxxwjm) {
        gx_fjxxwjm = gx_fjxxwjm;
    }

    public string getgx_fjxxtypt() {
        return gx_fjxxtypt;
    }

    public void setgx_fjxxtypt(string gx_fjxxtypt) {
        gx_fjxxtypt = gx_fjxxtypt;
    }

    public string getgx_fjxxwjlj() {
        return gx_fjxxwjlj;
    }

    public void setgx_fjxxwjlj(string gx_fjxxwjlj) {
        gx_fjxxwjlj = gx_fjxxwjlj;
    }

    public string getgx_fjxxyllj() {
        return gx_fjxxyllj;
    }

    public void setgx_fjxxyllj(string gx_fjxxyllj) {
        gx_fjxxyllj = gx_fjxxyllj;
    }

    public string getusercode() {
        return usercode;
    }

    public void setusercode(string usercode) {
        usercode = usercode;
    }


    public string getmsg() {
        return msg;
    }

    public void setmsg(string msg) {
        msg = msg;
    }
    
    
}

 

转换pdf代码:(注:此方法在servlet层调用进行处理)

package or.og.jxldemo;

import java.io.bufferedinputstream;
import java.io.file;
import java.io.ioexception;
import java.io.inputstream;

import javax.servlet.http.httpservletrequest;

import com.artofsolving.jodconverter.documentconverter;
import com.artofsolving.jodconverter.openoffice.connection.openofficeconnection;
import com.artofsolving.jodconverter.openoffice.connection.socketopenofficeconnection;
import com.artofsolving.jodconverter.openoffice.converter.openofficedocumentconverter;
import com.pantech.base.common.tools.mytools;
  

  
/** 
 * doc docx格式转换 
 *  
 * @author administrator 
 *  
 */  
public class office2swf {  
    private static final int environment = 1;// 环境 1:windows 2:linux  
    // (只涉及pdf2swf路径问题)  
    private string filestring;  
    private string outputpath = "";//输入路径 ,如果不设置就输出在默认的位置  
    private string filename;  
    private file pdffile;  
    private file swffile;  
    private file docfile;
    private string msg;
    
    private httpservletrequest request;
    
    public office2swf(httpservletrequest request, string filestring) {
        this.request = request;
        init(filestring);  
    }  
   
    /** 
     * 重新设置file 
     *  
     * @param filestring 
     */  
    public void setfile(string filestring) {  
        init(filestring);  
    }  
  
    /** 
     * 初始化 
     *  
     * @param filestring 
     */  
    private void init(string filestring) {  
        this.filestring = filestring;  
        filename = filestring.substring(0, filestring.lastindexof("."));  
        docfile = new file(filestring);  
        pdffile = new file(filename + ".pdf");  
        swffile = new file(filename + ".swf");  
    } 
    
    /** 
     * 转为pdf 
     *  
     * @param file 
     */  
    private void doc2pdf() throws exception {  
        if (docfile.exists()) {  
            if (!pdffile.exists()) {  
                try {
                    openofficeconnection connection = new socketopenofficeconnection("127.0.0.1", 8100);  
                    connection.connect();  
                    documentconverter converter = new openofficedocumentconverter(connection);  
                    converter.convert(docfile, pdffile);  
                    // close the connection  
                    connection.disconnect();  
                    system.out.println("****pdf转换成功,pdf输出:" + pdffile.getpath() + "****");  
                } catch (java.net.connectexception e) {  
                    e.printstacktrace();  
                    system.out.println("****swf转换器异常,openoffice服务未启动!****");
                    runtime rt = runtime.getruntime();
                    string batpath = mytools.getprop(request, "base.openofficebatpath");
                    java.io.file file = new java.io.file(batpath);  
                    // 检查bat文件是否存在  
                    if (file.isfile() && file.exists()) {
                         rt.exec(batpath);
                         this.setmsg("openoffice服务未启动");
                    }else{
                        this.setmsg("openofficebat文件不存在");
                    }
                   
                    throw e;  
                } catch (com.artofsolving.jodconverter.openoffice.connection.openofficeexception e) {  
                    e.printstacktrace();  
                    system.out.println("****swf转换器异常,读取转换文件失败****");  
                    throw e;  
                } catch (exception e) {  
                    e.printstacktrace();  
                    throw e;  
                }  
            } else {  
                system.out.println("****已经转换为pdf,不需要再进行转化****");  
            }  
        } else {  
            system.out.println("****swf转换器异常,需要转换的文档不存在,无法转换****");  
        }  
    }
    
    /**
     * 转换成 swf
     */
    private void pdf2swf(boolean flag) throws exception {
        runtime r = runtime.getruntime();
        if (!swffile.exists()) {
            if (pdffile.exists()) {
                if (environment == 1) {// windows环境处理
                    try {
                        string swftoolspath = mytools.getprop(request, "base.swftoolspath");
                        process p = r.exec(swftoolspath + " "+ pdffile.getpath() + " -o "+ swffile.getpath() + " -t 9 -s languagedir=c:/xpdf/xpdf-chinese-simplified");
                        system.out.print(loadstream(p.getinputstream()));
                        system.err.print(loadstream(p.geterrorstream()));
                        system.out.print(loadstream(p.getinputstream()));
                        system.out.println("****swf转换成功,文件输出:"    + swffile.getpath() + "****");
                        if (pdffile.exists() && flag) { //pdf文件存在并且源文件不是pdf格式
                            pdffile.delete();
                        }

                    } catch (ioexception e) {
                        e.printstacktrace();
                        throw e;
                    }
                } else if (environment == 2) {// linux环境处理
                    try {
                        process p = r.exec("pdf2swf " + pdffile.getpath() + " -o " + swffile.getpath() + " -t 9 -s languagedir=c:/xpdf/xpdf-chinese-simplified");
                        system.out.print(loadstream(p.getinputstream()));
                        system.err.print(loadstream(p.geterrorstream()));
                        system.err.println("****swf转换成功,文件输出:" + swffile.getpath() + "****");
                        if (pdffile.exists()) {
                            pdffile.delete();
                        }
                    } catch (exception e) {
                        e.printstacktrace();
                        throw e;
                    }
                }
            } else {
                system.out.println("****pdf不存在,无法转换****");
            }
        } else {
            system.out.println("****swf已经存在不需要转换****");
        }
    }

    static string loadstream(inputstream in) throws ioexception {
        int ptr = 0;
        in = new bufferedinputstream(in);
        stringbuffer buffer = new stringbuffer();

        while ((ptr = in.read()) != -1) {
            buffer.append((char) ptr);
        }

        return buffer.tostring();
    }

    /**
     * 转换主方法
     */
    public boolean conver() {
        boolean flag = false;
        if (swffile.exists()) {
            system.out.println("****swf转换器开始工作,该文件已经转换为swf****");
            return true;
        }

        if (environment == 1) {
            system.out.println("****swf转换器开始工作,当前设置运行环境windows****");
        } else {
            system.out.println("****swf转换器开始工作,当前设置运行环境linux****");
        }
        try {
            if (!pdffile.exists()) {
                flag = true;
                doc2pdf();
                pdf2swf(flag);
            }else{
                pdf2swf(flag);
            }
        } catch (exception e) {
            e.printstacktrace();
            return false;
        }

        if (swffile.exists()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 返回文件路径
     * 
     * @param s
     */
    public string getswfpath() {
        if (swffile.exists()) {
            string tempstring = swffile.getpath();
            tempstring = tempstring.replaceall("\\\\", "/");
            return tempstring;
        } else {
            return "";
        }
    }

    /**
     * 设置输出路径
     */
    public void setoutputpath(string outputpath) {
        this.outputpath = outputpath;
        if (!outputpath.equals("")) {
            string realname = filename.substring(filename.lastindexof("/"),
                    filename.lastindexof("."));
            if (outputpath.charat(outputpath.length()) == '/') {
                swffile = new file(outputpath + realname + ".swf");
            } else {
                swffile = new file(outputpath + realname + ".swf");
            }
        }
    }
    
    /**
     *  get&&set方法
     */
    public string getfilestring() {
        return filestring;
    }

    public void setfilestring(string filestring) {
        this.filestring = filestring;
    }

    public string getfilename() {
        return filename;
    }

    public void setfilename(string filename) {
        this.filename = filename;
    }

    public file getpdffile() {
        return pdffile;
    }

    public void setpdffile(file pdffile) {
        this.pdffile = pdffile;
    }

    public file getswffile() {
        return swffile;
    }

    public void setswffile(file swffile) {
        this.swffile = swffile;
    }

    public file getdocfile() {
        return docfile;
    }

    public void setdocfile(file docfile) {
        this.docfile = docfile;
    }

    public string getoutputpath() {
        return outputpath;
    }
    
    public string getmsg() {
        return msg;
    }

    public void setmsg(string msg) {
        msg = msg;
    }

}