java中使用jxl导出Excel表格

通过java操作excel表格的工具类库

支持Excel 95-2000的所有版本

生成Excel 2000标准格式

支持字体、数字、日期操作

能够修饰单元格属性

支持图像和图表

应该说以上功能已经能够大致满足我们的需要。最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。另外需要说明的是,这套API对图形和图表的支持很有限,而且仅仅识别PNG格式。

以上内容转自百度百科


综上所述,我们只要导入jxl.jar包就算是把环境搭建好了,下面就来演示一下使用jxl导出Excel的步骤:

以下代码可实现简单的导出操作(只要按规范封装好需要的参数,不支持合并行、列等一系列复杂的布局)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/**
  * Excel导出(Test)
  * @author Think-XiaoRong
  *
  */
public class ImportExcelFile {
                                                                
     /**
      * 导出Excel
      * @param list:结果集合
      * @param filePath:指定的路径名
      * @param out:输出流对象 通过response.getOutputStream()传入
      * @param mapFields:导出字段 key:对应实体类字段    value:对应导出表中显示的中文名
      * @param sheetName:工作表名称
      */
     public static void createExcel(List list,String filePath,OutputStream out,Map<String, String> mapFields,String sheetName){
         sheetName = sheetName!= null && !sheetName.equals( "" )?sheetName: "sheet1" ;
         WritableWorkbook wook = null ; //可写的工作薄对象
         Object objClass = null ;
         try {
             if (filePath!= null && !filePath.equals( "" )){
                 wook = Workbook.createWorkbook( new File(filePath)); //指定导出的目录和文件名 如:D:\\test.xls
             } else {
                 wook = Workbook.createWorkbook(out); //jsp页面导出用
             }
                                                                            
             //设置头部字体格式
             WritableFont font = new WritableFont(WritableFont.TIMES, 10 , WritableFont.BOLD,
                     false , UnderlineStyle.NO_UNDERLINE, Colour.RED);
             //应用字体
             WritableCellFormat wcfh = new WritableCellFormat(font);
             //设置其他样式
             wcfh.setAlignment(Alignment.CENTRE); //水平对齐
             wcfh.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直对齐
             wcfh.setBorder(Border.ALL, BorderLineStyle.THIN); //边框
             wcfh.setBackground(Colour.YELLOW); //背景色
             wcfh.setWrap( false ); //不自动换行
                                                                            
             //设置内容日期格式
             DateFormat df = new DateFormat( "yyyy-MM-dd HH:mm:ss" );
             //应用日期格式
             WritableCellFormat wcfc = new WritableCellFormat(df);
                                                                            
             wcfc.setAlignment(Alignment.CENTRE);
             wcfc.setVerticalAlignment(VerticalAlignment.CENTRE); //垂直对齐
             wcfc.setBorder(Border.ALL, BorderLineStyle.THIN); //边框
             wcfc.setWrap( false ); //不自动换行
                                                                            
             //创建工作表
             WritableSheet sheet = wook.createSheet(sheetName, 0 );
             SheetSettings setting = sheet.getSettings();
             setting.setVerticalFreeze( 1 ); //冻结窗口头部
                                                                            
             int columnIndex = 0 //列索引
             List<String> methodNameList = new ArrayList<String>();
             if (mapFields!= null ){
                 String key  = "" ;
                 Map<String,Method> getMap = null ;
                 Method method = null ;
                 //开始导出表格头部
                 for (Iterator<String> i = mapFields.keySet().iterator();i.hasNext();) {
                     key = i.next();
                     // 应用wcfh样式创建单元格
                     sheet.addCell( new Label(columnIndex, 0 , mapFields.get(key), wcfh));
                     //记录字段的顺序,以便于导出的内容与字段不出现偏移
                     methodNameList.add(key);
                     columnIndex++;
                 }
                 if (list!= null && list.size()> 0 ){
                     //导出表格内容
                     for ( int i = 0 ,len = list.size(); i < len; i++) {
                         objClass = list.get(i);
                         getMap = getAllMethod(objClass); //获得对象所有的get方法
                         //按保存的字段顺序导出内容
                         for ( int j = 0 ; j < methodNameList.size(); j++) {
                             //根据key获取对应方法
                             method = getMap.get( "GET" +methodNameList.get(j).toString().toUpperCase());
                             if (method!= null ){
                                 //从对应的get方法得到返回值
                                 String value = method.invoke(objClass, null ).toString();
                                 //应用wcfc样式创建单元格
                                 sheet.addCell( new Label(j, i+ 1 , value, wcfc));
                               } else {
                                    //如果没有对应的get方法,则默认将内容设为""
                                    sheet.addCell( new Label(j, i+ 1 , "" , wcfc));
                               }
                    
                         }
                     }
                 }
                 wook.write();
                 System.out.println( "导出Excel成功!" );
             } else {
                 throw new Exception( "传入参数不合法" );
             }
         } catch (Exception e) {
             e.printStackTrace();
         } finally {
             try {
                 if (wook!= null ){
                     wook.close();
                 }
                 if (out!= null ){
                     out.close();
                 }
             } catch (Exception e2) {
                 e2.printStackTrace();
             }
         }
     }
                                                                    
     /**
      * 获取类的所有get方法
      * @param cls
      * @return
      */
     public static HashMap<String,Method> getAllMethod(Object obj) throws Exception{
         HashMap<String,Method> map = new HashMap<String,Method>();
         Method[] methods = obj.getClass().getMethods(); //得到所有方法
         String methodName = "" ;
         for ( int i = 0 ; i < methods.length; i++) {
             methodName = methods[i].getName().toUpperCase(); //方法名
             if (methodName.startsWith( "GET" )){
                 map.put(methodName, methods[i]); //添加get方法至map中
             }
         }
         return map;
     }
                                                                    
     /**
      * 根据指定路径导出Excel
      * @param list
      * @param filePath
      * @param mapFields
      * @param sheetName
      */
     public static void ImportExcel(List list,String filePath,Map<String, String> mapFields,String sheetName){
         createExcel(list,filePath, null ,mapFields,sheetName);
     }
                                                                    
     /**
      * 从Jsp页面导出Excel
      * @param list
      * @param filePath
      * @param out
      * @param mapFields
      * @param sheetName
      */
     public static void ImportExcel(List list,OutputStream out,Map<String, String> mapFields,String sheetName){
         createExcel(list, null ,out,mapFields,sheetName);
     }
                                                                    
     public static void main(String[] args) {
         //测试
         UserView user = new UserView();
         user.setAddress( "深圳" );
         user.setName( "张三" );
         user.setSex( "男" );
         user.setAge( "22" );
         List list = new ArrayList();
         list.add(user); //将user实体添加到list
         Map<String,String> map = new LinkedHashMap<String, String>();
         //设置导出的字段。其中map中的key必须与实体类中的字段一致,不区分大小写,这里需要注意的是:请确保实体类中给导出的字段提供了set、get方法,不然会取不到值
         map.put( "name" , "姓名" );
         map.put( "sex" , "性别" );
         map.put( "age" , "年龄" );
         map.put( "address" , "地址" );
         ImportExcel(list, "E:\\test.xls" , map, "员工信息" );
     }
}

JSP页面导出,Action层代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
HttpServletResponse response = ServletActionContext.getResponse();
response.reset(); //清除缓存
//设置下载类型
response.setContentType( "application/x-download" );
String fileName = "汇交款清单.xls" ; //文件名
//设置下载文件名
response.addHeader( "Content-Disposition" , "attachment;filename=" +
new String(fileName.getBytes( "gb2312" ), "iso8859-1" ));
//设置导出字段  其中map中的key必须与实体类中的字段一致,不区分大小写
Map<String, String> mapField = new LinkedHashMap<String, String>();
mapField.put( "receipts_id" , "单据id" );
mapField.put( "cust_name" , "客户名称" );
mapField.put( "receipts_money" , "单据金额" );
mapField.put( "usable_money" , "可用金额" );
mapField.put( "account_date" , "到账日期" );
mapField.put( "account_remark" , "到账备注" );
mapField.put( "account_bank" , "到账银行" );
mapField.put( "cust_bank_account" , "客户银行账号" );
//调用导出方法  listInfo是从数据库查询出来并且已经封装好了的集合对象
ImportExcelFile.ImportExcel(listInfo, response.getOutputStream(), mapField, "汇交款清单" );
return null ; //因为是导出方法,文件下载完成后直接跳出

效果图:


以上代码亲测可行,因为是演示,所以写了一些多余的代码,实际开发中,只需要createExcelgetAllMethod两个方法即可

总结一下使用jxl导出Excel的步骤:

1.创建一个工作薄  WritableWorkbook wook = Workbook.createWorkbook(out)

2.使用WritableFont设置字体样式

3.使用WritableCellFormat设置单元格样式以及绑定字体样式

4.创建工作表 WritableSheet sheet = wook.createSheet(工作表名称, 工作表索引); //索引从0开始

5.使用sheet.addCell(new Label(列索引,行索引,内容,自定义的单元格样式))方法创建单元格

6.调用wookwrite方法导出

7.最后调用wook的close方法关闭流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值