使用JXL导出和解析EXCEL文件

来源:互联网 发布:arena软件官网 编辑:程序博客网 时间:2024/03/29 12:51

http://aiappfine.iteye.com/blog/289487

前些日子在做一个项目时,经常需要将一些数据导出到EXCEL文件中,而且操作很类似--一个标题,然后是子标题接着是一个列表。于是对其进行抽象,写了另一个类,完成了关键的处理。 

  1.     ws.setColumnView(i, colsSize[i]);  
  2.                             }  
  3.                         } else {  
  4.                             // 设置默认的宽度  
  5.                             for (int i = 0; i < colsNum; i++) {  
  6.                                 ws.setColumnView(i, 20);  
  7.                             }  
  8.                             result = Constant.EXPORT_EXCEL_ARRAYNOTHESAME_EXCEPTION;  
  9.                         }  
  10.                     }                 
  11.                     // 写EXCEL  
  12.                     wwb.write();  
  13.                     // 关闭资源  
  14.                     wwb.close();  
  15.                 } catch (IOException e) {  
  16.                     result = Constant.EXPORT_EXCEL_NOFILE_EXCEPTION;  
  17.                     e.printStackTrace();  
  18.                 } catch (RowsExceededException e) {  
  19.                     result = Constant.EXPORT_EXCEL_SYSTEM_EXCEPTION;  
  20.                     e.printStackTrace();  
  21.                 } catch (WriteException e) {  
  22.                     result = Constant.EXPORT_EXCEL_SYSTEM_EXCEPTION;  
  23.                     e.printStackTrace();  
  24.                 }  
  25.             }  
  26.         }  
  27.         return result;  
  28.     }  
  29.       
  30.     /** 
  31.      * 生成EXCEL通过浏览器导出到客户端,带比较全面的参数列表,在WEB项目中使用 
  32.      *  
  33.      * @param title 标题 
  34.      * @param hasInnerTitle 子标题,如果传入NULL,就不生成子标题。 
  35.      * @param colsSize 每列的宽度,如果传入的列数和LIST中的数组长度不一致,将会按默认的宽度处理 
  36.      * @param data EXCEL列表数据源 
  37.      * @param path 文件存放路径 
  38.      * @return 
  39.      */  
  40.     public static int exportExcelInWeb(String title,  
  41.             String innerTitle, int[] colsSize, List<String[]> data,  
  42.             OutputStream os) {  
  43.         int result = 1;  
  44.           
  45.         int colsNum=0;  
  46.         // 先判断是否传入原始数据  
  47.         if (data == null || data.size() == 0) {  
  48.             result = Constant.EXPORT_EXCEL_NO_DATA;           
  49.         } else {                          
  50.             // 判断传入的流             
  51.             if (os != null) {  
  52.                 // 生成EXCEL文件  
  53.                 WritableWorkbook wwb = null;  
  54.                 try {  
  55.                     wwb = Workbook.createWorkbook(os);  
  56.                     Label lable = new Label(00"学生信息列表", ExcelProperties.getHeader());                 
  57.                     // 创建EXCEL工作表  
  58.                     WritableSheet ws = wwb.createSheet("默认"0);  
  59.                     ws.addCell(lable);  
  60.                     // 取得LIST中的数组大小  
  61.                     colsNum=data.get(0).length;  
  62.                     // 参数的含义为:左列,左行,右列,右行 合并成一个单元格  
  63.                     ws.mergeCells(00, colsNum-10);  
  64.                     // 处理内标题  
  65.                     if(!StringUtil.isNullOrEmpty(innerTitle)){  
  66.                         lable = new Label(01, innerTitle, ExcelProperties.getHeaderInner());  
  67.                         ws.addCell(lable);  
  68.                         ws.mergeCells(01, colsNum-11);  
  69.                     }  
  70.                                           
  71.                     int flag = 0;  
  72.                     for (String temp[] : data) {  
  73.                         if (colsNum == temp.length) {  
  74.                             for (int i = 0; i < temp.length; i++) {  
  75.                                 lable = new Label(i, flag + ExcelProperties.dataRowBeginSize(!StringUtil.isNullOrEmpty(innerTitle)), temp[i],  
  76.                                         ExcelProperties.getNormolCell());  
  77.                                 ws.addCell(lable);  
  78.                             }  
  79.                             flag++;  
  80.                         }else{  
  81.                             result=Constant.EXPORT_EXCEL_ARRAYNOTHESAME_EXCEPTION;  
  82.                         }  
  83.                     }  
  84.                       
  85.                     //   
  86.                     if (result != Constant.EXPORT_EXCEL_ARRAYNOTHESAME_EXCEPTION) {  
  87.                         // 设置列宽  
  88.                         if (colsSize.length == colsNum) {  
  89.                             for (int i = 0; i < colsSize.length; i++) {  
  90.                                 ws.setColumnView(i, colsSize[i]);  
  91.                             }  
  92.                         } else {  
  93.                             // 设置默认的宽度  
  94.                             for (int i = 0; i < colsNum; i++) {  
  95.                                 ws.setColumnView(i, 20);  
  96.                             }  
  97.                             result = Constant.EXPORT_EXCEL_ARRAYNOTHESAME_EXCEPTION;  
  98.                         }  
  99.                     }                 
  100.                       
  101.                     wwb.write();  
  102.                     wwb.close();  
  103.                     os.close();  
  104.                 } catch (IOException e) {  
  105.                     result = Constant.EXPORT_EXCEL_NOFILE_EXCEPTION;  
  106.                     e.printStackTrace();  
  107.                 } catch (RowsExceededException e) {  
  108.                     result = Constant.EXPORT_EXCEL_SYSTEM_EXCEPTION;  
  109.                     e.printStackTrace();  
  110.                 } catch (WriteException e) {  
  111.                     result = Constant.EXPORT_EXCEL_SYSTEM_EXCEPTION;  
  112.                     e.printStackTrace();  
  113.                 }  
  114.             }else{  
  115.                 result = Constant.EXPORT_EXCEL_NULL_OUTPUTSTREAM_EXCEPTION;  
  116.             }  
  117.         }  
  118.         return result;  
  119.     }  
  120. }  


使用模拟数据的ArrayList对象,在main()方法中进行测试可以生成下面的EXCE文件,代码如下: 
Java代码  收藏代码
  1. package test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. public class DataMock {  
  7.   
  8.     /** 
  9.      * 模拟数据 
  10.      *  
  11.      * @return 
  12.      */  
  13.     public static List<String[]> getListData() {  
  14.         List<String[]> list = new ArrayList<String[]>();  
  15.         String[] temp=null;  
  16.         temp=new String[5];  
  17.         temp[0]="姓名";  
  18.         temp[1]="年龄";  
  19.         temp[2]="性别";  
  20.         temp[3]="身高";  
  21.         temp[4]="爱好";  
  22.         for (int i = 0; i < 50; i++) {  
  23.             temp=new String[5];  
  24.             temp[0]="学生"+i;  
  25.             temp[1]="12";  
  26.             temp[2]=i%2==0?"男":"女";  
  27.             temp[3]="1.60"+(i/10*3);  
  28.             temp[4]="篮球,乒乓球";  
  29.             list.add(temp);  
  30.         }  
  31.         return list;  
  32.     }  
  33.   
  34. }  


调用的代码: 
Java代码  收藏代码
  1. int result=ExportExcel.exportExcelToFileSystem("学生信息管理","(TWEB集团附属小学)",new int[]{24,24,18,16,20},DataMock.getListData(), "d:\\");  
  2.         System.out.println("result:"+result);  

运行以后就可以在D盘生成一个EXCEL。 

在C/S项目中,通过输出流直接向客户端输出,JSP代码里或Web框架的Action里调用代码为: 
Java代码  收藏代码
  1. <%@ page language="java" pageEncoding="UTF-8"%>  
  2. <%@page import="java.io.OutputStream"%>  
  3. <%@page import="cn.com.tweb.common.excel.ExportExcel"%>  
  4. <%@page import="test.DataMock"%>  
  5. <%@page import="cn.com.tweb.common.StringUtil"%>  
  6. <%    
  7.   
  8.   // 设定输出文件头  
  9.   response.setCharacterEncoding("GBK");  
  10.   // 当文件名为中文时请用StringUtil类的toUtf8String()方法进行转码  
  11.   response.setHeader("Content-disposition",  
  12.             "attachment;  filename="+StringUtil.toUtf8String("学生信息管理列表.xls"));  
  13.   // 定义输出类型  
  14.   response.setContentType("application/vnd.ms-excel");                 
  15.   OutputStream os = response.getOutputStream();  
  16.         
  17.   int result=ExportExcel.exportExcelInWeb("学生信息管理","(拓旗集团附属小学)",  
  18.             new int[]{24,24,18,16,20},DataMock.getListData(),os);  
  19.   System.out.println("-------------(result:"+result+")-------------");  
  20. %>  


常量接口类的代码为: 
Java代码  收藏代码
  1. package cn.com.tweb.common;  
  2. /** 
  3.  * 常量接口,以EXPORT_EXCEL_开头的变量,值大于0的都是导出EXCEL成功 
  4.  *  
  5.  * @author ZHANGWEIGUO 
  6.  * @version Revision: 1001  Date: 2006-09-03 05:00:21 +0800  
  7.  * @see  
  8.  * @see 
  9.  */  
  10. public interface Constant {  
  11.     // 成功导出EXCEL文件  
  12.     public static final int EXPORT_EXCEL_SUCCESS=1;  
  13.       
  14.     // 没有数据  
  15.     public static final int EXPORT_EXCEL_NO_DATA=-1;  
  16.   
  17.     // 系统异常  
  18.     public static final int EXPORT_EXCEL_SYSTEM_EXCEPTION=-2;  
  19.       
  20.     // 其他异常  
  21.     public static final int EXPORT_EXCEL_OTHER_EXCEPTION=-3;  
  22.       
  23.     // 文件路径和文件名无效  
  24.     public static final int EXPORT_EXCEL_NOFILE_EXCEPTION=-4;  
  25.       
  26.     // 集合对象中的数组存放的数据个数不一致  
  27.     public static final int EXPORT_EXCEL_ARRAYNOTHESAME_EXCEPTION=-5;  
  28.       
  29.     // 传入的OUTPUTSTREAM为空  
  30.     public static final int EXPORT_EXCEL_NULL_OUTPUTSTREAM_EXCEPTION=-6;  
  31.       
  32.     // 宽度设置参数有误,按默认值设定宽度  
  33.     public static final int EXPORT_EXCEL_COLSNUM_NOTRIGHT=2;  
  34.       
  35. }  

解析EXCEL文件的代码如下: 
Java代码  收藏代码
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import jxl.Cell;  
  7. import jxl.Sheet;  
  8. import jxl.Workbook;  
  9. import jxl.read.biff.BiffException;  
  10.   
  11. import org.apache.commons.fileupload.FileItem;  
  12.   
  13. public class ParseExcel {  
  14.       
  15.     /** 
  16.      *  用COMMON UPLOAD进行EXCEL文件上传,得到fileItem对象,这里 
  17.      * 进行解析,返回集合对象。该方法适合在JAVA工程中使用。 
  18.      *  
  19.      * @param fileItem 
  20.      * @param beginIndex 正式数据的起始行 例如EXCEL文件 
  21.      *  有大标题和小标题和列标题,那么该参数应为 4 
  22.      * @return 
  23.      * @throws BiffException 
  24.      * @throws IOException 
  25.      */  
  26.     public static List<String[]> redExcel(FileItem fileItem,int beginIndex){  
  27.         // 保存结果集  
  28.         List<String[]> result=null;  
  29.         // 保存EXCEL每行的所有单元格中的数据  
  30.         String[] temp=null;  
  31.         try {  
  32.             if (fileItem != null) {  
  33.                 Workbook workBook = Workbook.getWorkbook(fileItem  
  34.                         .getInputStream());  
  35.                 Sheet sheet = workBook.getSheet(0);  
  36.                 Cell cell = null;  
  37.                 int rowSize = sheet.getRows();  
  38.                 int colSize = sheet.getColumns();  
  39.   
  40.                 result = new ArrayList<String[]>();  
  41.                 for (int i = beginIndex - 1; i < rowSize; i++) {  
  42.                     temp = new String[colSize];  
  43.                     for (int t = 0; t < colSize; t++) {                        
  44.                         // 保存EXCEL每行的所有单元格中的数据,在内循环外面进行定义  
  45.                         cell = sheet.getCell(t, i);  
  46.                         String content = "";  
  47.                         if (cell.getContents() != null) {  
  48.                             // 去空格,特殊字符和回车键盘  
  49.                             content = cell.getContents().replace("%""")  
  50.                                     .replace("|""").replace(" """)  
  51.                                     .replaceAll("\\n""")  
  52.                                     .replaceAll("\\r""").trim();  
  53.   
  54.                         }  
  55.                         temp[t] = content;  
  56.                     }  
  57.                     // 将每列的的数据存入结果集中  
  58.                     result.add(temp);  
  59.                 }  
  60.             }  
  61.         } catch (Exception ex) {  
  62.             ex.printStackTrace();  
  63.         }  
  64.         return result;  
  65.     }  
  66.       
  67.     /** 
  68.      *  用COMMON UPLOAD进行EXCEL文件上传,得到fileItem对象,这里 
  69.      * 进行解析,返回集合对象。该方法适合在WEB项目中使用。 
  70.      *  
  71.      * @param fileItem 
  72.      * @param beginIndex 正式数据的起始行 例如EXCEL文件 
  73.      *  有大标题和小标题和列标题,那么该参数应为 4 
  74.      * @return 
  75.      * @throws BiffException 
  76.      * @throws IOException 
  77.      */  
  78.     public static List<String[]> redExcel(File file,int beginIndex){  
  79.         // 保存结果集  
  80.         List<String[]> result=null;  
  81.         // 保存EXCEL每行的所有单元格中的数据  
  82.         String[] temp=null;  
  83.         try {  
  84.             Workbook workBook = Workbook.getWorkbook(file);  
  85.             Sheet sheet = workBook.getSheet(0);  
  86.             Cell cell = null;  
  87.             int rowSize = sheet.getRows();  
  88.             int colSize = sheet.getColumns();  
  89.               
  90.             result=new ArrayList<String[]>();  
  91.             for (int i = beginIndex-1; i < rowSize; i++) {  
  92.                 // 保存EXCEL每行的所有单元格中的数据  
  93.                 temp=new String[colSize];  
  94.                 for (int t = 0; t < colSize; t++) {                    
  95.                     cell = sheet.getCell(t, i);  
  96.                     String content="";  
  97.                     if (cell.getContents()!=null) {  
  98.                         // 去空格,特殊字符和回车键盘  
  99.                         content = cell.getContents().replace("%""")  
  100.                                 .replace("|""")  
  101.                                 .replace(" """)  
  102.                                 .replaceAll("\\n""")  
  103.                                 .replaceAll("\\r""").trim();  
  104.                           
  105.                     }  
  106.                     temp[t]=content;                      
  107.                 }  
  108.                 // 将每列的的数据存入结果集中  
  109.                 result.add(temp);  
  110.             }  
  111.         } catch (Exception ex) {  
  112.             ex.printStackTrace();  
  113.         }  
  114.         return result;  
  115.     }     
  116. }