`

再次封装POI,读写EXCEL。

阅读更多
直接上code
package com.sinosoft.lis.pubfun;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2004</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

import com.sinosoft.utility.StrTool;
import com.sinosoft.utility.DBConnPool;
import java.io.*;
import java.util.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.*;

public class ExportExcel {
    public static class Format{
        public ArrayList mListCell=null;
        public ArrayList mListBL = null;
        public ArrayList mListColWidth = null;
    }
    public static class Cell{
        public Cell(){}
        public int col;
        public int row;
        public int width=1;
        public int height=1;
        public boolean bBorder=false;
        public boolean bBold=false;
        public String content="";
    }

    public static class ListBlock{
        private String companyCode;
        public ListBlock(String str){companyCode = str;};

        public String[] colName=null;
        public String sql;
        public int row1=0;
        public int col1=0;
        public int row2;
        public int col2;
        public int size=0;
        public String[][] data=null;
        public boolean InitData(){
            if(sql==null||sql.equals(""))
                return false;
            Connection conn=null;
            try{
                conn=DBConnPool.getConnection();
                if (conn==null)
                {
                    System.out.println("数据库连接失败!");
                    return false;
                }
                data = exeSQL(sql,conn);
                if(data==null){
                    row2=row1;
                    col2=col1;
                    if(colName!=null){
                        row2++;
                        col2+=colName.length;
                    }
                }
                else{
                    row2=row1+data.length;
                    size=data.length;
                    if(colName!=null){
                        row2++;
                        col2=col1+colName.length;
                    }
                    else if(data.length>1){
                        col2=col1+data[0].length;
                    }
                    else
                        col2=col1;
                }
            }
            catch(Exception e){
                System.out.println(e);return false;
            }
            finally{
                try{conn.close();}catch(Exception e){};
            }
            return true;
        }
    }

    public static void AddCellToList(ArrayList list,String text,int row,int col,int width,int height,boolean bBorder,boolean bBold){
        Cell tCell = new Cell();
        tCell.row=row;
        tCell.col=col;
        tCell.bBorder=bBorder;
        tCell.bBold=bBold;
        tCell.height=height;
        tCell.width=width;
        tCell.content=text;
        list.add(tCell);
    }

    public ExportExcel() {
    }


    public boolean write(Format format,BufferedOutputStream bos)
    {
        if(format==null)
            return false;
        ArrayList listCell = format.mListCell;
        ArrayList listLB = format.mListBL;
        ArrayList listColWidth = format.mListColWidth;

        if(null==listCell && null==listLB)
            return false;
        if(null==bos)
            return false;

        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("new sheet");

        try{

        if(listColWidth!=null){
            for(int i=0;i<listColWidth.size();i++){
                String[] para = (String[])listColWidth.get(i);
                short nCol = (short)Integer.parseInt(para[0]);
                short nWidth = (short)Integer.parseInt(para[1]);
                sheet.setColumnWidth(nCol,nWidth);
            }
        }

        // Create a new font and alter it.
        HSSFFont fontBold = wb.createFont();
        fontBold.setFontHeightInPoints((short)10);
        fontBold.setFontName("宋体");
        fontBold.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontNormal = wb.createFont();
        fontNormal.setFontHeightInPoints((short)10);
        fontNormal.setFontName("宋体");
        fontNormal.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

        HSSFCellStyle styleBorderBold = wb.createCellStyle();
        styleBorderBold.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleBorderBold.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styleBorderBold.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styleBorderBold.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styleBorderBold.setFont(fontBold);

        HSSFCellStyle styleBorderNormal = wb.createCellStyle();
        styleBorderNormal.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleBorderNormal.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styleBorderNormal.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styleBorderNormal.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styleBorderNormal.setFont(fontNormal);

        HSSFCellStyle styleBold = wb.createCellStyle();
        styleBold.setFont(fontBold);

        HSSFCellStyle styleNormal = wb.createCellStyle();
        styleNormal.setFont(fontNormal);

        if(listLB!=null){
            for(int iLB=0;iLB<listLB.size();iLB++){
                ListBlock currLB = (ListBlock)listLB.get(iLB);
                int startRow = currLB.row1;
                for(int i=0;currLB.colName!=null&&i<currLB.colName.length;i++){
                    int rowIndex = startRow;
                    int colIndex = currLB.col1+i;
                    HSSFRow row = sheet.getRow(rowIndex);
                    if(row==null)
                        row = sheet.createRow(rowIndex);
                    HSSFCell cell = row.getCell((short)colIndex);
                    if(cell==null)
                        cell = row.createCell((short)colIndex);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    cell.setCellStyle(styleBorderBold);
                    cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                    cell.setCellValue(currLB.colName[i]);
                }

                if(currLB.colName!=null)
                    startRow=currLB.row1+1;

                String[][] data = currLB.data;
                if(data!=null){
                    for(int i=0;i<data.length;i++){
                        for(int j=0;j<data[i].length;j++){
                            int rowIndex = startRow+i;
                            int colIndex = currLB.col1+j;

                            HSSFRow row = sheet.getRow(rowIndex);
                            if(row==null)
                                row = sheet.createRow(rowIndex);
                            HSSFCell cell = row.getCell((short)colIndex);
                            if(cell==null)
                                cell = row.createCell((short)colIndex);
                            cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                            cell.setCellStyle(styleBorderNormal);
                            cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                            cell.setCellValue(data[i][j]);
                        }
                    }
                }
            }
        }


        if(listCell!=null){
            for(int i=0;i<listCell.size();i++){
                Cell currCell = (Cell)listCell.get(i);
                for(int j=currCell.row;j<currCell.row+currCell.height;j++){
                    for(int k=currCell.col;k<currCell.col+currCell.width;k++){
                        HSSFRow trow = sheet.getRow(j);
                        if(trow==null)
                            trow = sheet.createRow(j);
                        HSSFCell tcell = trow.getCell((short)k);
                        if(tcell==null)
                            tcell = trow.createCell((short)k);
                        tcell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        tcell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        if(j==currCell.row&&k==currCell.col)
                            tcell.setCellValue(currCell.content);
                        if(currCell.bBorder){
                            if(currCell.bBold)
                                tcell.setCellStyle(styleBorderBold);
                            else
                                tcell.setCellStyle(styleBorderNormal);
                        }
                        else{
                            if(currCell.bBold)
                                tcell.setCellStyle(styleBold);
                            else
                                tcell.setCellStyle(styleNormal);
                        }
                    }
                }
                if(currCell.height>1||currCell.width>1)
                    sheet.addMergedRegion(new Region(currCell.row,(short)currCell.col,currCell.row+currCell.height-1,(short)(currCell.col+currCell.width-1)));
            }
        }

        wb.write(bos);
        }
        catch(Exception e){
            System.out.println(e);
            return false;
        }

        return true;
    }


    public static String[][] exeSQL(String sql,String companyCode){
        String[][] retArray = null;

        Statement stmt = null;
        ResultSet rs = null;
        ResultSetMetaData rsmd = null;
        String mResult = "";
        ArrayList tempList = new ArrayList();

        System.out.println("ExportExcel.exeSQL() : " + sql.trim());
        Connection conn=null;
        conn=DBConnPool.getConnection();
        if (conn==null)
        {
          System.out.println("数据库连接失败!");
          return null;
        }

        try {
            stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY );

            rs = stmt.executeQuery( StrTool.GBKToUnicode( sql ));
            rsmd = rs.getMetaData();
            int n = rsmd.getColumnCount();
            int k = 0;

            // 取得总记录数
            while( rs.next() ) {
                String[] tempRow = new String[n];
                k++;
                for( int j = 1; j <= n; j++ ) {
                    String strValue = "";
                    //根据数据类型取得数据的值
                    strValue = getDataValue( rsmd, rs, j );
                    tempRow[j-1] = strValue;
                }
                tempList.add(tempRow);
            }
            rs.close();
            stmt.close();

            if(tempList.size()>0){
            retArray = new String[tempList.size()][];
            for(int i=0;i<tempList.size();i++){
                String[] row = (String[])tempList.get(i);
                retArray[i]=row;
                //for(int j=0;j<row.length;j++){
                //    retArray[i][j] = row[j];
                //}
            }
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            try{ rs.close(); stmt.close(); } catch( Exception ex ) {}
        }
        finally{
                try{conn.close();} catch( Exception ex ) {}
        }

        return retArray;
    }

    public static String[][] exeSQL(String sql,Connection conn){
        String[][] retArray = null;

        Statement stmt = null;
        ResultSet rs = null;
        ResultSetMetaData rsmd = null;
        String mResult = "";
        ArrayList tempList = new ArrayList();

        System.out.println("ExportExcel.exeSQL() : " + sql.trim());
        boolean connflag=true;
        if (conn==null)
        {
          System.out.println("数据库连接失败!");
          return null;
        }

        try {
            stmt = conn.createStatement( ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY );

            rs = stmt.executeQuery( StrTool.GBKToUnicode( sql ));
            rsmd = rs.getMetaData();
            int n = rsmd.getColumnCount();
            int k = 0;

            // 取得总记录数
            while( rs.next() ) {
                String[] tempRow = new String[n];
                k++;
                for( int j = 1; j <= n; j++ ) {
                    String strValue = "";
                    //根据数据类型取得数据的值
                    strValue = getDataValue( rsmd, rs, j );
                    tempRow[j-1] = strValue;
                }
                tempList.add(tempRow);
            }
            rs.close();
            stmt.close();

            if(tempList.size()>0){
            retArray = new String[tempList.size()][];
            for(int i=0;i<tempList.size();i++){
                String[] row = (String[])tempList.get(i);
                retArray[i]=row;
                //for(int j=0;j<row.length;j++){
                //    retArray[i][j] = row[j];
                //}
            }
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            try{ rs.close(); stmt.close(); } catch( Exception ex ) {}
        }
        return retArray;
    }


    public static String getDataValue( ResultSetMetaData rsmd, ResultSet rs, int i )
    {
      String strValue = "";
      try
      {
        int dataType = rsmd.getColumnType( i );
        int dataScale = rsmd.getScale( i );
        int dataPrecision =rsmd.getPrecision(i);
        if( dataType == Types.CHAR || dataType == Types.VARCHAR ) strValue = StrTool.unicodeToGBK( rs.getString( i ));
        if( dataType == Types.TIMESTAMP || dataType == Types.DATE ) strValue = (new FDate()).getString( rs.getDate( i ));
        if( dataType == Types.DECIMAL || dataType == Types.DOUBLE ) strValue = String.valueOf( rs.getDouble( i ));
        if( dataType == Types.INTEGER || dataType == Types.SMALLINT ) strValue = String.valueOf( rs.getInt( i ));
        if( dataType == Types.NUMERIC )
        {
          if( dataScale == 0 )
          {
            if (dataPrecision==0)
              strValue = String.valueOf( rs.getDouble(i));
            else
              strValue = String.valueOf( rs.getLong(i));
          }
          else{
            strValue = String.valueOf(rs.getBigDecimal(i));
            System.out.println("BigDecimal: The Numeric is = "+strValue);
          }
        }
        if(strValue == null)
            strValue = "";
        strValue = PubFun.getInt(strValue);
      }
      catch( Exception ex ){}

      return strValue;
  }


    public static void main(String[] args) {
        ExportExcel excel = new ExportExcel();
        try{
            ExportExcel.Format format = new ExportExcel.Format();
            ArrayList listCell = new ArrayList();
            ArrayList listLB = new ArrayList();
            ArrayList listColWidth = new ArrayList();
            format.mListCell=listCell;
            format.mListBL=listLB;
            format.mListColWidth=listColWidth;

            listColWidth.add(new String[]{"0","5000"});

//            ExportExcel.Cell tCell = new ExportExcel.Cell();
//            tCell.row=0;
//            tCell.col=0;
//            tCell.bBorder=true;
//            tCell.height=1;
//            tCell.width=5;
//            tCell.content="边框";
//            listCell.add(tCell);
//
//            tCell = new ExportExcel.Cell();
//            tCell.row=1;
//            tCell.col=0;
//            tCell.bBorder=false;
//            tCell.height=1;
//            tCell.width=5;
//            tCell.content="无边框";
//            listCell.add(tCell);

           // ExportExcel.ListBlock tLB = new ExportExcel.ListBlock("001");
            //tLB.colName=new String[]{"编号","姓名"};
//            tLB.sql="select * from lduser ";
//            tLB.col1=0;
//            tLB.row1=2;
//            tLB.InitData();
//            listLB.add(tLB);

            ExportExcel.ListBlock tLB1 = new ExportExcel.ListBlock("001");
//            tLB1.colName=new String[]{"集体合同号码","合同号码","被保人客户号","印刷号码","投保人客户号码","管理机构","处理机构","家庭保障号","与主被保人关系","与投保人关系","客户地址号码","客户内部号码","被保人名称","被保人性别","被保人出生日期","证件类型",
//						                          "证件号码","国籍","民族","户口所在地","婚姻状况","结婚日期","健康状况","身高","体重","学历","信用等级","银行编码","银行帐号","银行帐户名","入司日期","参加工作日期","职位","工资","职业类别","职业代码",
//												  "职业(工种)","兼职(工种)","是否吸烟标志","保险计划编码","操作员","被保人状态","入机日期","入机时间","最后一次修改日期","最后一次修改时间","核保状态","最终核保人编码","核保完成日期","核保完成时间","","被保人数目"};

			tLB1.colName=new String[]{"集体合同号码","被保人客户号","姓名","性别","出生日期","证件类型","证件号码","保险计划"};
            tLB1.sql="select Grpcontno,InsuredNo,Name,Sex,Birthday,IDType,IDNo,ContPlanCode From LCInsured where Grpcontno='140110000000041'";
            //tLB1.sql="select * From LDuser";
			tLB1.col1=0;
            //tLB1.row1=tLB.row2+10;
			tLB1.row1=0;
            tLB1.InitData();
            listLB.add(tLB1);

            File of = new File("d:\\excel.xls");
            FileOutputStream ofs = new FileOutputStream(of);
            BufferedOutputStream bos = new BufferedOutputStream(ofs);
            excel.write(format,bos);
        }
        catch(Exception e){System.out.println(e);}
        finally{}

    }

}

封装类的使用
<%@page contentType="text/html;charset=GBK" %>
<%@page import="java.util.*" %>
<%@page import="java.io.*" %>
<%@page import="com.sinosoft.lis.pubfun.*"%>
<%@page import="com.sinosoft.utility.*"%>
<%
//在此设置导出Excel的列名,应与sql语句取出的域相对应
GlobalInput tGlobalInput = new GlobalInput(); 
tGlobalInput = (GlobalInput)session.getValue("GI");   
ExportExcel.Format format = new ExportExcel.Format();
ArrayList listCell = new ArrayList();
ArrayList listLB = new ArrayList();
ArrayList listColWidth = new ArrayList();
format.mListCell=listCell;
format.mListBL=listLB;
format.mListColWidth=listColWidth;
ExportExcel.Cell tCell=null;
ExportExcel.ListBlock tLB=null;

String tManageCom = tGlobalInput.ComCode;
String SerialNo ="0000000001";
String ExportExcelSQL =request.getParameter("ExportExcelSQL");
System.out.println("Excel语句="+ExportExcelSQL);
listColWidth.add(new String[]{"0","5000"});  
String sql = ExportExcelSQL;
tLB = new ExportExcel.ListBlock("001");
tLB.colName = new String[]{"管理机构","管理机构名称","代理人编码","代理人姓名","证件类型编码","证件类型名称","证件号码","二次入司标记","入司职级","","入司标志","入司日期","离职日期","序列号"  };
tLB.sql = sql;
tLB.row1 = 0;
tLB.col1 = 0;
tLB.InitData();
listLB.add(tLB);
try
{
	  response.reset();
    response.setContentType("application/octet-stream");    
    //设置导出的xls文件名默认值
    String HeaderParam = "\""+"attachment;filename="+SerialNo+".xls"+"\"";
    System.out.println("导出文件名称:"+HeaderParam);
    response.setHeader("Content-Disposition",HeaderParam);
    OutputStream outOS = response.getOutputStream();
    BufferedOutputStream bos = new BufferedOutputStream(outOS);
    ExportExcel excel = new ExportExcel();
    excel.write(format, bos);
    bos.flush();
    bos.close();
}
catch(Exception e)
{
    System.out.println("导出Excel失败!");
 %>
 <script language="JavaScript" type="text/javascript">
 alert("导出Excel失败!");
 </script>>
 <%   
};
%>
分享到:
评论
1 楼 wanghonghui023 2010-08-19  
楼主把架包共享依稀啊啊

import com.sinosoft.utility.StrTool;  
import com.sinosoft.utility.DBConnPool;  


我的邮箱:amama_110@yahoo.com.cn  多谢

相关推荐

    java中poi读写excel封装工具类(兼容office2003和2007等版本)

    java中poi读写excel封装工具类(兼容office2003和2007等版本),绝对可用的例子!

    POI操作Excel的封装

    通过反射和相应的约定实现POI操作Excel的封装

    基于POI的Excel操作Java类

    为更方便的使用POI的API来操作Excel(2003)文件,对POI中针对Excel文件的读写进行了简单封装。此类中包含以下功能: 1.根据模板创建Excel文件 2.获取及更新Excel文件内容 3.创建、复制Sheet 4.设置Sheet名称 ... ...

    一个java用POI组件读写Excel的类

    一个java用POI读写Excel的类封装了一个读取Excel数据的方法和一个写入Excel数据的方法,写入的话可从数据库读取或自己写一个List...

    Java用POI API实现对Excel表的读取与写入,包含对数据库的读写,亲测有效

    1、POI_EXCEL包下分别有两个类,一个是读取excel内容,一个是想excel写入内容 2、cn.itcast包下的所有包,是为了实现从excel写入到数据库中,和从数据库写入到excel中 注意事项: 1、需要导入maven工程 2、使用...

    java poi对于excel的读写与反射的结合使用

    java poi对于excel的读写与反射的结合使用,2个方法读2个方法写,是单独的源码文件,结合反射的方法读写各一个,还有个是list的2层集合excel读写方法,还包含使用到的简单函数封装

    poi简单的封装工具

    简易封装poi, 将文件与对象直接进行映射, 可以快速读写文件。方便快捷的更专注于业务。 什么时候开始资源描述需要50个字以上了,简直看不懂这个操作,是不是蠢啊

    POI web导入导出类封装!

    poi即Excel导入导出,在开发过程中了,为了提高数据录入速度, 一些系统都会使用导入功能,导入目前只能通过流的方式读写,那么为了此操作的便利性,提供此工具类,是原有的excel数据读取到泛型集合中,然后再对集合...

    java读写excel2010

    自己封装的java读写excel2010的库,拿来直接用!操作更简单!样例请查看:http://blog.ijustyce.com/?post=359

    Excel读写类(无需office环境)

    Excel读写类库,封装其他几个有POI类库实现对Excel文件的读取和保存数据到Excel,比较实用强大! 此Excel读写类库,比调用DotNet自带office库,强大。自己已经比较,稳定性、效率都大大提高。 DotNet自带Excel类库...

    excel文件读写工具

    excel文件读写工具,针对xls,xlsx及csv 读写封装成的jar,使用poi实现

    apache.poi所需要的jar包集合

    版本:4.1.0 jar包个数:7个 apache的poi,操作Excel的包,亲测 jdk11 maven项目环境下包含本地jar使用有效,并给出了简单易用的封装。 传送门:我的博文:基于poi4.1.0的Excel表读写操作 日期:2020.12.15日

    Java读写Excel文件,JXL框架工具类

    问题:目前,无论是JXL还是POI,对Excel的操作都是比较原始的,用户无法使用这些框架代码直接读取Excle并相应相应的数据实体(Entity),也无法直接将数据实体写入到Excle文件中去。 本文章要介绍的是一个对JXL框架...

    EasyExcel JAVA解析Excel工具 v3.3.4

    03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便。 特征: 快速 快速的读取excel中的数据。 简洁 映射excel和实体类,让代码变的更加简洁。 大文件 在读写大文件的时候使用磁盘做...

    eaasyexcel批量导入+校验

    EasyExcel重写了POI对07Excel的解析,解决一部分了内存消耗特大的问题03版本任依赖POI的SAX模式 EasyExcel特点 1.数据模型层面进行了封装,...5.读写Excel,数据在excel文件,程序&lt;实体类,MAP&gt;两个载体之间 互相流转

    Java范例开发大全 (源程序)

     实例139 利用POI读取Word文件中的内容 208  7.3 字符流 209  实例140 按顺序创建文件 210  实例141 按顺序读取文件 211  实例142 追加文件内容 211  实例143 只显示文件中指定的字符 214  实例144 ...

    java范例开发大全(pdf&源码)

    实例139 利用POI读取Word文件中的内容 208 7.3 字符流 209 实例140 按顺序创建文件 210 实例141 按顺序读取文件 211 实例142 追加文件内容 211 实例143 只显示文件中指定的字符 214 实例144 读取jar包文件 215 实例...

    java范例开发大全源代码

     实例139 利用POI读取Word文件中的内容 208  7.3 字符流 209  实例140 按顺序创建文件 210  实例141 按顺序读取文件 211  实例142 追加文件内容 211  实例143 只显示文件中指定的字符 214  实例...

    java范例开发大全

    实例139 利用POI读取Word文件中的内容 208 7.3 字符流 209 实例140 按顺序创建文件 210 实例141 按顺序读取文件 211 实例142 追加文件内容 211 实例143 只显示文件中指定的字符 214 实例144 读取jar包文件 215 实例...

    Java范例开发大全(全书源程序)

    实例139 利用POI读取Word文件中的内容 208 7.3 字符流 209 实例140 按顺序创建文件 210 实例141 按顺序读取文件 211 实例142 追加文件内容 211 实例143 只显示文件中指定的字符 214 实例144 读取jar包文件 ...

Global site tag (gtag.js) - Google Analytics