jxl导入/导出excel

  1 package junit.test;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import jxl.Cell;
  9 import jxl.Sheet;
 10 import jxl.Workbook;
 11 import jxl.write.Label;
 12 import jxl.write.Number;
 13 import jxl.write.WritableImage;
 14 import jxl.write.WritableSheet;
 15 import jxl.write.WritableWorkbook;
 16 import jxl.write.WriteException;
 17 
 18 import org.apache.commons.lang3.math.NumberUtils;
 19 import org.junit.Test;
 20 
 21 /**
 22  * Excel导入导出
 23  * 
 24  * @author 林计钦
 25  * @version 1.0 Feb 7, 2014 4:14:51 PM
 26  */
 27 public class ExcelTest {
 28 
 29     /**
 30      * 导入(导入到内存)
 31      */
 32     @Test
 33     public void importExcel() {
 34         Workbook book = null;
 35         try {
 36             book = Workbook.getWorkbook(new File("D:/test/测试.xls"));
 37             // 获得第一个工作表对象
 38             Sheet sheet = book.getSheet(0);
 39             int rows=sheet.getRows();
 40             int columns=sheet.getColumns();
 41             // 遍历每行每列的单元格
 42             for(int i=0;i<rows;i++){
 43                 for(int j=0;j<columns;j++){
 44                     Cell cell = sheet.getCell(j, i);
 45                     String result = cell.getContents();
 46                     if(j==0){
 47                         System.out.print("姓名:"+result+" ");
 48                     }
 49                     if(j==1){
 50                         System.out.print("年龄:"+result+" ");
 51                     }
 52                     if((j+1)%2==0){ 
 53                         System.out.println();
 54                     }
 55                 }
 56             }
 57             System.out.println("========");
 58             // 得到第一列第一行的单元格
 59             Cell cell1 = sheet.getCell(0, 0);
 60             String result = cell1.getContents();
 61             System.out.println(result);
 62             System.out.println("========");
 63         } catch (Exception e) {
 64             System.out.println(e);
 65         }finally{
 66             if(book!=null){
 67                 book.close();
 68             }
 69         }
 70     }
 71 
 72     /**
 73      * 导出(导出到磁盘)
 74      */
 75     @Test
 76     public void exportExcel() {
 77         WritableWorkbook book = null;
 78         try {
 79             // 打开文件
 80             book = Workbook.createWorkbook(new File("D:/test/测试.xls"));
 81             // 生成名为"学生"的工作表,参数0表示这是第一页
 82             WritableSheet sheet = book.createSheet("学生", 0);
 83             // 指定单元格位置是第一列第一行(0, 0)以及单元格内容为张三
 84             Label label = new Label(0, 0, "张三");
 85             // 将定义好的单元格添加到工作表中
 86             sheet.addCell(label);
 87             // 保存数字的单元格必须使用Number的完整包路径
 88             jxl.write.Number number = new jxl.write.Number(1, 0, 30);
 89             sheet.addCell(number);
 90             // 写入数据并关闭文件
 91             book.write();
 92         } catch (Exception e) {
 93             System.out.println(e);
 94         }finally{
 95             if(book!=null){
 96                 try {
 97                     book.close();
 98                 } catch (Exception e) {
 99                     e.printStackTrace();
100                 } 
101             }
102         }
103     }
104     
105     /**
106      * 对象数据写入到Excel
107      */
108     @Test
109     public void writeExcel() {
110         WritableWorkbook book = null;
111         try {
112             // 打开文件
113             book = Workbook.createWorkbook(new File("D:/test/stu.xls"));
114             // 生成名为"学生"的工作表,参数0表示这是第一页
115             WritableSheet sheet = book.createSheet("学生", 0);
116             
117             List<Student> stuList=queryStudentList();
118             if(stuList!=null && !stuList.isEmpty()){
119                 for(int i=0; i<stuList.size(); i++){
120                     sheet.addCell(new Label(0, i, stuList.get(i).getName()));
121                     sheet.addCell(new Number(1, i, stuList.get(i).getAge()));
122                 }
123             }
124             
125             // 写入数据并关闭文件
126             book.write();
127         } catch (Exception e) {
128             System.out.println(e);
129         }finally{
130             if(book!=null){
131                 try {
132                     book.close();
133                 } catch (Exception e) {
134                     e.printStackTrace();
135                 } 
136             }
137         }
138     
139     }
140     
141     /**
142      * 读取Excel数据到内存
143      */
144     @Test
145     public void readExcel() {
146         Workbook book = null;
147         try {
148             // 打开文件
149             book = Workbook.getWorkbook(new File("D:/test/stu.xls"));
150             // 获得第一个工作表对象
151             Sheet sheet = book.getSheet(0);
152             int rows=sheet.getRows();
153             int columns=sheet.getColumns();
154             List<Student> stuList=new ArrayList<Student>();
155             // 遍历每行每列的单元格
156             for(int i=0;i<rows;i++){
157                 Student stu = new Student();
158                 for(int j=0;j<columns;j++){
159                     Cell cell = sheet.getCell(j, i);
160                     String result = cell.getContents();
161                     if(j==0){
162                         stu.setName(result);
163                     }
164                     if(j==1){
165                         stu.setAge(NumberUtils.toInt(result));
166                     }
167                     if((j+1)%2==0){
168                         stuList.add(stu);
169                         stu=null;
170                     }
171                 }
172             }
173             
174             //遍历数据
175             for(Student stu : stuList){
176                 System.out.println(String.format("姓名:%s, 年龄:%s", 
177                         stu.getName(), stu.getAge()));
178             }
179             
180         } catch (Exception e) {
181             System.out.println(e);
182         }finally{
183             if(book!=null){
184                 try {
185                     book.close();
186                 } catch (Exception e) {
187                     e.printStackTrace();
188                 } 
189             }
190         }
191     
192     }
193     
194     /**
195      * 图片写入Excel,只支持png图片
196      */
197     @Test
198     public void writeImg() {
199         WritableWorkbook wwb = null;
200         try {
201             wwb = Workbook.createWorkbook(new File("D:/test/image.xls"));
202             WritableSheet ws = wwb.createSheet("图片", 0);
203             File file = new File("D:\test\png.png");
204             //前两位是起始格,后两位是图片占多少个格,并非是位置
205             WritableImage image = new WritableImage(1, 4, 6, 18, file);
206             ws.addImage(image);
207             wwb.write();
208         } catch (Exception e) {
209             e.printStackTrace();
210         }finally{
211             if(wwb!=null){
212                 try {
213                     wwb.close();
214                 } catch (Exception e) {
215                     e.printStackTrace();
216                 }  
217             }
218         }
219     }
220     
221     private List<Student> queryStudentList(){
222         List<Student> stuList=new ArrayList<Student>();
223         stuList.add(new Student("zhangsan", 20));
224         stuList.add(new Student("lisi", 25));
225         stuList.add(new Student("wangwu", 30));
226         return stuList;
227     }
228     
229     public class Student {
230         private String name;
231         private int age;
232 
233         public Student() {
234         }
235 
236         public Student(String name, int age) {
237             super();
238             this.name = name;
239             this.age = age;
240         }
241 
242         public String getName() {
243             return name;
244         }
245 
246         public void setName(String name) {
247             this.name = name;
248         }
249 
250         public int getAge() {
251             return age;
252         }
253 
254         public void setAge(int age) {
255             this.age = age;
256         }
257     }
258 }
View Code

2、jxl常用操作
a、数据格式化
在Excel中不涉及复杂的数据类型,能够比较好的处理字符串、数字和日期已经能够满足一般的应用。

字串格式化
字符串的格式化涉及到的是字体、粗细、字号等元素,这些功能主要由WritableFont和WritableCellFormat类来负责。假设我们在生成一个含有字串的单元格时,使用如下语句,为方便叙述,我们为每一行命令加了编号:

① WritableFont font1= new WritableFont(WritableFont.TIMES, 16, WritableFont.BOLD); 或//设置字体格式为excel支持的格式 WritableFont font3=new WritableFont(WritableFont.createFont("楷体 _GB2312"), 12, WritableFont.NO_BOLD);
② WritableCellFormat format1=new WritableCellFormat(font1);
③ Label label=new Label(0, 0, "data 4 test", format1);

其中,
①指定了字串格式:字体为TIMES,字号16,加粗显示。
WritableFont有非常丰富的构造子函数,供不同情况下使用,jExcelAPI的java-doc中有详细列表,这里不再列出。
②处代码使用了WritableCellFormat类,这个类非常重要,通过它可以指定单元格的各种属性,后面的单元格格式化中会有更多描述。 
③处使用了Label类的构造子,指定了字串被赋予那种格式。在WritableCellFormat类中,还有一个很重要的方法是指定数据的对齐方式,比如针对我们上面的实例,可以指定:

//把水平对齐方式指定为居中
format1.setAlignment(jxl.format.Alignment.CENTRE);
//把垂直对齐方式指定为居中
format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
//设置自动换行
format1.setWrap(true);

b、单元格操作
Excel中很重要的一部分是对单元格的操作,比如行高、列宽、单元格合并等,所幸jExcelAPI提供了这些支持。这些操作相对比较简单,下面只介绍一下相关的API。
1、合并单元格
//作用是从(m,n)到(p,q)的单元格全部合并
WritableSheet.mergeCells(int m, int n, int p, int q); 
比如:

WritableSheet sheet=book.createSheet("第一页", 0); 
//合并第一列第一行到第六列第一行的所有单元格
//合并既可以是横向的,也可以是纵向的。合并后的单元格不能再次进行合并,否则会触发异常。
sheet.mergeCells(0, 0, 5, 0);

c、行高和列宽
//作用是指定第i+1行的高度
WritableSheet.setRowView(int i, int height);
比如:将第一行的高度设为200

sheet.setRowView(0, 200);

//作用是指定第i+1列的宽度,
WritableSheet.setColumnView(int i,int width);
比如:将第一列的宽度设为30

sheet.setColumnView(0, 30);

d、操作图片(只支持png图片)

 1 /**
 2      * 图片写入Excel,只支持png图片
 3      */
 4     @Test
 5     public void writeImg() {
 6         WritableWorkbook wwb = null;
 7         try {
 8             wwb = Workbook.createWorkbook(new File("D:/test/image.xls"));
 9             WritableSheet ws = wwb.createSheet("图片", 0);
10             File file = new File("D:\test\png.png");
11             //前两位是起始格,后两位是图片占多少个格,并非是位置
12             WritableImage image = new WritableImage(1, 4, 6, 18, file);
13             ws.addImage(image);
14             wwb.write();
15         } catch (Exception e) {
16             e.printStackTrace();
17         }finally{
18             if(wwb!=null){
19                 try {
20                     wwb.close();
21                 } catch (Exception e) {
22                     e.printStackTrace();
23                 }  
24             }
25         }
26     }
操作图片

很简单和插入单元格的方式一样,不过就是参数多了些,WritableImage这个类继承了 Draw,上面只是他构造方法的一种,最后一个参数不用说了,前面四个参数的类型都是double,依次是 x, y, width, height,注意,这里的宽和高可不是图片的宽和高,而是图片所要占的单元格的个数,因为继承的Draw所以他的类型必须是double,具体里面怎么实现的我还没细看:)因为着急赶活,先完成功能,其他的以后有时间慢慢研究。以后会继续写出在使用中的心得给大家。

3、注意事项
a、jxl导出excel乱码
在导出excel时,发现中文的标题乱码,试了N种编码方式,开始总是试图转为utf-8、gb2312、gbk,没想到转为iso-8859-1中文乱码的问题解决了


fileName = new String(fileName.getBytes(),"iso-8859-1");
response.setCharacterEncoding("gb2312");
response.reset();
response.setContentType("application/OCTET-STREAM;charset=gb2312");
response.setHeader("pragma", "no-cache");
response.addHeader("Content-Disposition", "attachment;filename=""
+ fileName + ".xls"");// 点击导出excle按钮时候页面显示的默认名称
workbook = Workbook.createWorkbook(response.getOutputStream());

 
原文地址:https://www.cnblogs.com/yang1018/p/7170023.html