⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 outputexcelservlet.java

📁 excel打印模板,支持单表,主从关系表格,利用xml格式的office文档特点
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company:倚天软件 </p>
 *
 * @author 丁锋
 * @version 1.0
 */

import java.io.*;
import java.sql.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;
import org.jdom.xpath.*;


public class outputExcelServlet extends HttpServlet {
    public outputExcelServlet() {
        try {
            jbInit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static final String CONTENT_TYPE = "text/html; charset=GBK";

    //Initialize global variables
    public void init() throws ServletException {
    }

    //Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        //////////////////////////////////////////////////
        response.setContentType("application/ms-excel");
        response.setHeader("Content-Disposition",
                           "attachment;filename=" +
                           new String("请您打印.xls".getBytes(), "iso-8859-1"));
        //response.setHeader("Content-disposition","attachment; filename=book.xls" );

        String fileSeparator = System.getProperty("file.separator");
        String name = (this.getServletContext()).getRealPath("servlet");
        String path = tools.getServPath(name);
        String left= request.getParameter("left");
        //此处以下变量都需要参数传递,目前为了试验方便,采用固定的写法.
        String filePath = path + fileSeparator + "ExcelTemplate\\template.xls";
        String fileTmp  = path+fileSeparator+"ExcelTemplate\\template.xls";
        try {

            String sqlMaster= "select '测试单位'  单位 ";

            String sql = "select * from test";
            String sql1 = "select 日期 from test1";
            String sql2 = "select 单位 from test1";
            String sql3 = "select 客户 from test1";

            connectDB cnDBM=new connectDB();
            ResultSet rsM=cnDBM.getResultSet(sqlMaster);
            connectDB cnDB = new connectDB();
            ResultSet rs = cnDB.getResultSet(sql);
            connectDB cnDB1 = new connectDB();
            ResultSet rs1 = cnDB1.getResultSet(sql1);
            connectDB cnDB2 = new connectDB();
            ResultSet rs2 = cnDB2.getResultSet(sql2);
            connectDB cnDB3 = new connectDB();
            ResultSet rs3 = cnDB3.getResultSet(sql3);


          //  Document  doc= this.testxml();
          //======打印调用实例=======begin=========
           //得到数据源列表
            PrintDoc    printdoc=new PrintDoc();
            //宏参数
            printdoc.htMacroList.put("日期", "2005-5-24");
            printdoc.htMacroList.put("日期", "2005-5-24");
            //打印数据集
            printdoc.htResultList.put("查询主表",rsM);
            printdoc.htResultList.put("查询从表",rs);
            //打印模板
            printdoc.strFileTp="D:\\outputExcelServlet\\outputExcelServlet\\ExcelTemplate\\template.xml";
            //根据模板,数据源列表,宏参数数组,生成文档
            Document      doc= printdoc.printData();
            //输出文档
            XMLOutputter  xmlout=new XMLOutputter();
            xmlout.output(doc,response.getOutputStream());
            //======打印调用实例=======end=========

            rs.close();rs1.close();rs2.close();rs3.close();rsM.close();
            cnDB.close();cnDB1.close();cnDB2.close();cnDB3.close();cnDBM.close();

            System.out.println("测试成功!");

        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex){}

        /////////////////////////////////////////////////
    }

    //Process the HTTP Post request
    public void makeprint(String TemplateFile,ResultSet rs,Hashtable ht)
    {
        String nsp = "urn:schemas-microsoft-com:office:spreadsheet";

    }

    //Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }

    //Clean up resources
    public void destroy() {
    }

    private void jbInit() throws Exception {
    }

    private Document testxml() throws Exception
    {
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build("D:\\outputExcelServlet\\outputExcelServlet\\ExcelTemplate\\template.xml");

        // Print servlet information
        XPath xmlValuePath = XPath.newInstance("//ss:Cell[@ss:StyleID=\"s25\"]");
        //XPath xmlValuePath= XPath.newInstance("//Cell");
        xmlValuePath.addNamespace("","urn:schemas-microsoft-com:office:spreadsheet");
        xmlValuePath.addNamespace("o","urn:schemas-microsoft-com:office:office");
        xmlValuePath.addNamespace("x","urn:schemas-microsoft-com:office:excel");
        xmlValuePath.addNamespace("ss","urn:schemas-microsoft-com:office:spreadsheet");
        xmlValuePath.addNamespace("html","http://www.w3.org/TR/REC-html40");
        List xmlValueNodes = xmlValuePath.selectNodes(doc);
        Iterator i = xmlValueNodes.iterator();
        while (i.hasNext())
        {
            Element xmlValueNode = (Element) i.next();
            xmlValueNode.setAttribute("test","测试abc123");
            xmlValueNode.setAttribute("pixName",xmlValueNode.getNamespacePrefix());
            xmlValueNode.setAttribute("prefixUri",xmlValueNode.getNamespaceURI());
        }
        doc.getRootElement().setAttribute("test","测试Value"+xmlValueNodes.size());
        return doc;
    }



}
class   PrintDoc
{
        //定义表的规则配制
        //在摸板的第一个填写数据的单元格内设置了报表的数据源规则和打印范围规则
        //规则格式如下:
        //<数据表>数据源名称,别名,起点行号,起点列号,终点行号,终点列号,父数据源别名,下一条记录的行增量,下一条记录的列增量&数据源名称,别名,起点行号,起点列号,终点行号,终点列号,父数据源别名,下一条记录的行增量,下一条记录的列增量;
        //<参数>&参数名#,&参数名#;
        //<数据表>查询主表,a,1,1,24,13,,25,0&查询从表,b,6,3,21,12,a,1,0;<参数>&日期#,&单位#;
        //注意,对于主从关系的报表,设置主数据源时,要把“下一条记录的行增量”设置得超过一页,这样可以实现多单据的翻页
        //     对于明细数据,一般是一行显示一条记录,所以一般设置行增量为1,列增量为0;
        //     对于页合计,可以利用excel的本身功能,直接设置单元格相加,在翻页时,新的页上也会应用这些规则的
        class TableConfig
        {
            String   TableName="";  //数据集名称
            String   AliasName="";  //别名
            String   ParentAliasName=""; //父表别名
            int     StartRow=0;    //数据填充的范围:行起点
            int     StartCol=0;    //数据填充的范围:列起点
            int     EndRow=10;     //数据填充的范围:行终点
            int     EndCol=10;     //数据填充的范围:列终点
            int     IncRow=+1;     //数据填充的范围:行循环增量,增量超限页范围就换页
            int     IncCol=0;      //数据填充的范围:列循环增量,增量超限页范围就换页
            List    FieldList=new ArrayList();   //字段列表
            int     CurRow=-1;     //当前行,-1表示是新开始的数据绑定,是从数据的需要根据当前父记录过滤
        }

        class  FieldConfig
        {
            String   TableAliasName="";
            String   FieldName="";
            int      iRow=0;
            int      iCol=0;
        }
        //摸板文件位置
        public String   strFileTp="";
        //数据源列表
        public Hashtable htResultList=new Hashtable();
        //要打印的数据源配置数组
        private TableConfig[]    DBConfList=null;
        //使用的宏参数
        public Hashtable htMacroList=new Hashtable();

        //读取模板,写入数据源打印配置列表:htResultList是数据集列表,htMacroList是宏参数列表
        public Document printData( )  throws Exception
        {
            SAXBuilder builder = new SAXBuilder();
            Document doc = builder.build(this.strFileTp);
            XPath   xmlValuePath=this.newInstance("//ss:Data");
            //在摸板的第一个填写数据的单元格内设置了报表的数据源规则和打印范围规则
            Element  xmlConfigNode=(Element)xmlValuePath.selectSingleNode(doc);
            String    str=xmlConfigNode.getTextTrim();
            xmlConfigNode.removeContent();
            System.out.println(str);
            String[]  strArray=str.split(";");
            str=strArray[0].replaceFirst("<数据表>","");
            String[]  strDBList=str.split("&");
            //宏参数配置
            str=strArray[1];
            str=str.replaceAll("<参数>","");
            String[]  strMacroList=str.split(",");
            for(int i=0;i<strMacroList.length;i++)
            {
                strMacroList[i]=strMacroList[i].trim();
                if(strMacroList[i].startsWith("&") && strMacroList[i].endsWith("#") )
                    strMacroList[i]=strMacroList[i].substring(1,strMacroList[i].length()-1);
                System.out.println(strMacroList[i]);
            }
            //数据集配置
            this.DBConfList=new TableConfig[strDBList.length];
            for(int i=0;i<strDBList.length;i++)
            {
                DBConfList[i]=new TableConfig();

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -