POI导出EXCEL经典实现(附带jar包)

  在web开发中,有一个经典的功能,就是数据的导入导出。特别是数据的导出,在生产管理或者财务系统中用的非常普遍,因为这些系统经常要做一些报表打印的工作。而数据导出的格式一般是EXCEL或者PDF,我这里就用两篇文章分别给大家介绍下。(注意,我们这里说的数据导出可不是数据库中的数据导出!么误会啦^_^)

  呵呵,首先我们来导出EXCEL格式的文件吧。现在主流的操作Excel文件的开源工具有很多,用得比较多的就是Apache的POI及JExcelAPI。这里我们用Apache POI!我们先去Apache的大本营下载POI的jar包:http://poi.apache.org/,我这里使用的是3.0.2版本。

  将3个jar包导入到classpath下,什么?忘了怎么导包?不会吧!好,我们来写一个导出Excel的实用类(所谓实用,是指基本不用怎么修改就可以在实际项目中直接使用的!)。我一直强调做类也好,做方法也好,一定要通用性和灵活性强。下面这个类就算基本贯彻了我的这种思想。那么,熟悉许老师风格的人应该知道,这时候该要甩出一长串代码了。没错,大伙请看:

  1. packagecom.j.bean;
  2. publicclassBook{
  3. privateintbookId;
  4. privateStringname;
  5. privateStringauthor;
  6. privatefloatprice;
  7. privateStringisbn;
  8. privateStringpubName;
  9. privatebyte[]preface;
  10. publicBook(){
  11. super();
  12. }
  13. publicBook(intbookId,Stringname,Stringauthor,floatprice,
  14. Stringisbn,StringpubName,byte[]preface){
  15. super();
  16. this.bookId=bookId;
  17. this.name=name;
  18. this.author=author;
  19. this.price=price;
  20. this.isbn=isbn;
  21. this.pubName=pubName;
  22. this.preface=preface;
  23. }
  24. publicintgetBookId(){
  25. returnbookId;
  26. }
  27. publicvoidsetBookId(intbookId){
  28. this.bookId=bookId;
  29. }
  30. publicStringgetName(){
  31. returnname;
  32. }
  33. publicvoidsetName(Stringname){
  34. this.name=name;
  35. }
  36. publicStringgetAuthor(){
  37. returnauthor;
  38. }
  39. publicvoidsetAuthor(Stringauthor){
  40. this.author=author;
  41. }
  42. publicfloatgetPrice(){
  43. returnprice;
  44. }
  45. publicvoidsetPrice(floatprice){
  46. this.price=price;
  47. }
  48. publicStringgetIsbn(){
  49. returnisbn;
  50. }
  51. publicvoidsetIsbn(Stringisbn){
  52. this.isbn=isbn;
  53. }
  54. publicStringgetPubName(){
  55. returnpubName;
  56. }
  57. publicvoidsetPubName(StringpubName){
  58. this.pubName=pubName;
  59. }
  60. publicbyte[]getPreface(){
  61. returnpreface;
  62. }
  63. publicvoidsetPreface(byte[]preface){
  64. this.preface=preface;
  65. }
  66. }
  67. packagecom.j.bean;
  68. importjava.util.Date;
  69. publicclassStudent{
  70. privatelongid;
  71. privateStringname;
  72. privateintage;
  73. privatebooleansex;
  74. privateDatebirthday;
  75. publicStudent(){
  76. super();
  77. }
  78. publicStudent(longid,Stringname,intage,booleansex,Datebirthday){
  79. super();
  80. this.id=id;
  81. this.name=name;
  82. this.age=age;
  83. this.sex=sex;
  84. this.birthday=birthday;
  85. }
  86. publiclonggetId(){
  87. returnid;
  88. }
  89. publicvoidsetId(longid){
  90. this.id=id;
  91. }
  92. publicStringgetName(){
  93. returnname;
  94. }
  95. publicvoidsetName(Stringname){
  96. this.name=name;
  97. }
  98. publicintgetAge(){
  99. returnage;
  100. }
  101. publicvoidsetAge(intage){
  102. this.age=age;
  103. }
  104. publicbooleangetSex(){
  105. returnsex;
  106. }
  107. publicvoidsetSex(booleansex){
  108. this.sex=sex;
  109. }
  110. publicDategetBirthday(){
  111. returnbirthday;
  112. }
  113. publicvoidsetBirthday(Datebirthday){
  114. this.birthday=birthday;
  115. }
  116. }

上面这两个类一目了然,就是两个简单的javabean风格的类。再看下面真正的重点类:

  1. packagecom.j.util;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.FileInputStream;
  4. importjava.io.FileNotFoundException;
  5. importjava.io.FileOutputStream;
  6. importjava.io.IOException;
  7. importjava.io.OutputStream;
  8. importjava.lang.reflect.Field;
  9. importjava.lang.reflect.InvocationTargetException;
  10. importjava.lang.reflect.Method;
  11. importjava.text.SimpleDateFormat;
  12. importjava.util.ArrayList;
  13. importjava.util.Collection;
  14. importjava.util.Date;
  15. importjava.util.Iterator;
  16. importjava.util.List;
  17. importjava.util.regex.Matcher;
  18. importjava.util.regex.Pattern;
  19. importjavax.swing.JOptionPane;
  20. importorg.apache.poi.hssf.usermodel.HSSFCell;
  21. importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
  22. importorg.apache.poi.hssf.usermodel.HSSFClientAnchor;
  23. importorg.apache.poi.hssf.usermodel.HSSFComment;
  24. importorg.apache.poi.hssf.usermodel.HSSFFont;
  25. importorg.apache.poi.hssf.usermodel.HSSFPatriarch;
  26. importorg.apache.poi.hssf.usermodel.HSSFRichTextString;
  27. importorg.apache.poi.hssf.usermodel.HSSFRow;
  28. importorg.apache.poi.hssf.usermodel.HSSFSheet;
  29. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
  30. importorg.apache.poi.hssf.util.HSSFColor;
  31. importcom.j.bean.Book;
  32. importcom.j.bean.Student;
  33. publicclassExportExcel<T>{
  34. publicvoidexportExcel(Collection<T>dataset,OutputStreamout){
  35. exportExcel("测试POI导出EXCEL文档",null,dataset,out,"yyyy-MM-dd");
  36. }
  37. publicvoidexportExcel(String[]headers,Collection<T>dataset,
  38. OutputStreamout){
  39. exportExcel("测试POI导出EXCEL文档",headers,dataset,out,"yyyy-MM-dd");
  40. }
  41. publicvoidexportExcel(String[]headers,Collection<T>dataset,
  42. OutputStreamout,Stringpattern){
  43. exportExcel("测试POI导出EXCEL文档",headers,dataset,out,pattern);
  44. }
  45. /**
  46. *这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL的形式输出到指定IO设备上
  47. *
  48. *@paramtitle
  49. *表格标题名
  50. *@paramheaders
  51. *表格属性列名数组
  52. *@paramdataset
  53. *需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
  54. *javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
  55. *@paramout
  56. *与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
  57. *@parampattern
  58. *如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
  59. */
  60. @SuppressWarnings("unchecked")
  61. publicvoidexportExcel(Stringtitle,String[]headers,
  62. Collection<T>dataset,OutputStreamout,Stringpattern){
  63. //声明一个工作薄
  64. HSSFWorkbookworkbook=newHSSFWorkbook();
  65. //生成一个表格
  66. HSSFSheetsheet=workbook.createSheet(title);
  67. //设置表格默认列宽度为15个字节
  68. sheet.setDefaultColumnWidth((short)15);
  69. //生成一个样式
  70. HSSFCellStylestyle=workbook.createCellStyle();
  71. //设置这些样式
  72. style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
  73. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  74. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  75. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  76. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  77. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  78. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  79. //生成一个字体
  80. HSSFFontfont=workbook.createFont();
  81. font.setColor(HSSFColor.VIOLET.index);
  82. font.setFontHeightInPoints((short)12);
  83. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  84. //把字体应用到当前的样式
  85. style.setFont(font);
  86. //生成并设置另一个样式
  87. HSSFCellStylestyle2=workbook.createCellStyle();
  88. style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
  89. style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  90. style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  91. style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  92. style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
  93. style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
  94. style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  95. style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  96. //生成另一个字体
  97. HSSFFontfont2=workbook.createFont();
  98. font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  99. //把字体应用到当前的样式
  100. style2.setFont(font2);
  101. //声明一个画图的顶级管理器
  102. HSSFPatriarchpatriarch=sheet.createDrawingPatriarch();
  103. //定义注释的大小和位置,详见文档
  104. HSSFCommentcomment=patriarch.createComment(newHSSFClientAnchor(0,0,0,0,(short)4,2,(short)6,5));
  105. //设置注释内容
  106. comment.setString(newHSSFRichTextString("可以在POI中添加注释!"));
  107. //设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
  108. comment.setAuthor("leno");
  109. //产生表格标题行
  110. HSSFRowrow=sheet.createRow(0);
  111. for(shorti=0;i<headers.length;i++){
  112. HSSFCellcell=row.createCell(i);
  113. cell.setCellStyle(style);
  114. HSSFRichTextStringtext=newHSSFRichTextString(headers[i]);
  115. cell.setCellValue(text);
  116. }
  117. //遍历集合数据,产生数据行
  118. Iterator<T>it=dataset.iterator();
  119. intindex=0;
  120. while(it.hasNext()){
  121. index++;
  122. row=sheet.createRow(index);
  123. Tt=(T)it.next();
  124. //利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
  125. Field[]fields=t.getClass().getDeclaredFields();
  126. for(shorti=0;i<fields.length;i++){
  127. HSSFCellcell=row.createCell(i);
  128. cell.setCellStyle(style2);
  129. Fieldfield=fields[i];
  130. StringfieldName=field.getName();
  131. StringgetMethodName="get"
  132. +fieldName.substring(0,1).toUpperCase()
  133. +fieldName.substring(1);
  134. try{
  135. ClasstCls=t.getClass();
  136. MethodgetMethod=tCls.getMethod(getMethodName,
  137. newClass[]{});
  138. Objectvalue=getMethod.invoke(t,newObject[]{});
  139. //判断值的类型后进行强制类型转换
  140. StringtextValue=null;
  141. //if(valueinstanceofInteger){
  142. //intintValue=(Integer)value;
  143. //cell.setCellValue(intValue);
  144. //}elseif(valueinstanceofFloat){
  145. //floatfValue=(Float)value;
  146. //textValue=newHSSFRichTextString(
  147. //String.valueOf(fValue));
  148. //cell.setCellValue(textValue);
  149. //}elseif(valueinstanceofDouble){
  150. //doubledValue=(Double)value;
  151. //textValue=newHSSFRichTextString(
  152. //String.valueOf(dValue));
  153. //cell.setCellValue(textValue);
  154. //}elseif(valueinstanceofLong){
  155. //longlongValue=(Long)value;
  156. //cell.setCellValue(longValue);
  157. //}
  158. if(valueinstanceofBoolean){
  159. booleanbValue=(Boolean)value;
  160. textValue="男";
  161. if(!bValue){
  162. textValue="女";
  163. }
  164. }elseif(valueinstanceofDate){
  165. Datedate=(Date)value;
  166. SimpleDateFormatsdf=newSimpleDateFormat(pattern);
  167. textValue=sdf.format(date);
  168. }elseif(valueinstanceofbyte[]){
  169. //有图片时,设置行高为60px;
  170. row.setHeightInPoints(60);
  171. //设置图片所在列宽度为80px,注意这里单位的一个换算
  172. sheet.setColumnWidth(i,(short)(35.7*80));
  173. //sheet.autoSizeColumn(i);
  174. byte[]bsValue=(byte[])value;
  175. HSSFClientAnchoranchor=newHSSFClientAnchor(0,0,
  176. 1023,255,(short)6,index,(short)6,index);
  177. anchor.setAnchorType(2);
  178. patriarch.createPicture(anchor,workbook.addPicture(
  179. bsValue,HSSFWorkbook.PICTURE_TYPE_JPEG));
  180. }else{
  181. //其它数据类型都当作字符串简单处理
  182. textValue=value.toString();
  183. }
  184. //如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
  185. if(textValue!=null){
  186. Patternp=Pattern.compile("^//d+(//.//d+)?$");
  187. Matchermatcher=p.matcher(textValue);
  188. if(matcher.matches()){
  189. //是数字当作double处理
  190. cell.setCellValue(Double.parseDouble(textValue));
  191. }else{
  192. HSSFRichTextStringrichString=newHSSFRichTextString(textValue);
  193. HSSFFontfont3=workbook.createFont();
  194. font3.setColor(HSSFColor.BLUE.index);
  195. richString.applyFont(font3);
  196. cell.setCellValue(richString);
  197. }
  198. }
  199. }catch(SecurityExceptione){
  200. //TODOAuto-generatedcatchblock
  201. e.printStackTrace();
  202. }catch(NoSuchMethodExceptione){
  203. //TODOAuto-generatedcatchblock
  204. e.printStackTrace();
  205. }catch(IllegalArgumentExceptione){
  206. //TODOAuto-generatedcatchblock
  207. e.printStackTrace();
  208. }catch(IllegalAccessExceptione){
  209. //TODOAuto-generatedcatchblock
  210. e.printStackTrace();
  211. }catch(InvocationTargetExceptione){
  212. //TODOAuto-generatedcatchblock
  213. e.printStackTrace();
  214. }finally{
  215. //清理资源
  216. }
  217. }
  218. }
  219. try{
  220. workbook.write(out);
  221. }catch(IOExceptione){
  222. //TODOAuto-generatedcatchblock
  223. e.printStackTrace();
  224. }
  225. }
  226. publicstaticvoidmain(String[]args){
  227. //测试学生
  228. ExportExcel<Student>ex=newExportExcel<Student>();
  229. String[]headers={"学号","姓名","年龄","性别","出生日期"};
  230. List<Student>dataset=newArrayList<Student>();
  231. dataset.add(newStudent(10000001,"张三",20,true,newDate()));
  232. dataset.add(newStudent(20000002,"李四",24,false,newDate()));
  233. dataset.add(newStudent(30000003,"王五",22,true,newDate()));
  234. //测试图书
  235. ExportExcel<Book>ex2=newExportExcel<Book>();
  236. String[]headers2={"图书编号","图书名称","图书作者","图书价格","图书ISBN",
  237. "图书出版社","封面图片"};
  238. List<Book>dataset2=newArrayList<Book>();
  239. try{
  240. BufferedInputStreambis=newBufferedInputStream(
  241. newFileInputStream("book.jpg"));
  242. byte[]buf=newbyte[bis.available()];
  243. while((bis.read(buf))!=-1){
  244. //
  245. }
  246. dataset2.add(newBook(1,"jsp","leno",300.33f,"1234567",
  247. "清华出版社",buf));
  248. dataset2.add(newBook(2,"java编程思想","brucl",300.33f,"1234567",
  249. "阳光出版社",buf));
  250. dataset2.add(newBook(3,"DOM艺术","lenotang",300.33f,"1234567",
  251. "清华出版社",buf));
  252. dataset2.add(newBook(4,"c++经典","leno",400.33f,"1234567",
  253. "清华出版社",buf));
  254. dataset2.add(newBook(5,"c#入门","leno",300.33f,"1234567",
  255. "汤春秀出版社",buf));
  256. OutputStreamout=newFileOutputStream("E://a.xls");
  257. OutputStreamout2=newFileOutputStream("E://b.xls");
  258. ex.exportExcel(headers,dataset,out);
  259. ex2.exportExcel(headers2,dataset2,out2);
  260. out.close();
  261. JOptionPane.showMessageDialog(null,"导出成功!");
  262. System.out.println("excel导出成功!");
  263. }catch(FileNotFoundExceptione){
  264. //TODOAuto-generatedcatchblock
  265. e.printStackTrace();
  266. }catch(IOExceptione){
  267. //TODOAuto-generatedcatchblock
  268. e.printStackTrace();
  269. }
  270. }
  271. }

  不行,头有点晕^_^。呵呵,又是泛型,又是反射,又是正则表达式,又是重载,还有多参数列表和POI API。一下子蹦出来,实在让人吃不消。不管了,顶住看效果先。在本地运行后,我们发现在E://下生成了两份excel文件:学生记录和图书记录,并且中文,数字,颜色,日期,图片等等一且正常。恩,太棒了。有人看到这里开始苦脸了:喂,我怎么一运行就报错啊!呵呵,看看什么错吧!哦,找不到文件,也就是说你没有book.jpg嘛。好,拷贝一张小巧的图书图片命名为book.jpg放置到当前工程下吧。注意,您千万别把张桌面大小的图片丢进去了^_^!看到效果了吧。现在我们再来简单梳理一下代码,实际上上面就做了一个导出excel的方法和一个本地测试main()方法。并且代码的结构也很清晰,只是涉及的知识点稍微多一点。大家细心看看注释,结合要完成的功能,应该没有太大问题的。好啦,吃杯茶,擦把汗,总算把这个类消化掉,你又进步了。咦,你不是说是在WEB环境下导出的吗?别急,因为导出就是一个下载的过程。我们只需要在服务器端写一个Jsp或者Servlet组件完成输出excel到浏览器客户端的工作就好了。我们以Servlet为例,还是看代码吧:

  1. packagecom.j.servlet;
  2. importjava.io.BufferedInputStream;
  3. importjava.io.File;
  4. importjava.io.FileInputStream;
  5. importjava.io.FileNotFoundException;
  6. importjava.io.IOException;
  7. importjava.io.OutputStream;
  8. importjava.util.ArrayList;
  9. importjava.util.List;
  10. importjavax.servlet.ServletException;
  11. importjavax.servlet.http.HttpServlet;
  12. importjavax.servlet.http.HttpServletRequest;
  13. importjavax.servlet.http.HttpServletResponse;
  14. importcom.j.bean.Book;
  15. importcom.j.util.ExportExcel;
  16. publicclassExcelServletextendsHttpServlet{
  17. staticfinallongserialVersionUID=1L;
  18. protectedvoiddoGet(HttpServletRequestrequest,
  19. HttpServletResponseresponse)throwsServletException,IOException{
  20. Filefile=newFile(getServletContext()
  21. .getRealPath("WEB-INF/book.jpg"));
  22. response.setContentType("octets/stream");
  23. response.addHeader("Content-Disposition",
  24. "attachment;filename=test.xlsx");
  25. //测试图书
  26. ExportExcel<Book>ex=newExportExcel<Book>();
  27. String[]headers={"图书编号","图书名称","图书作者","图书价格","图书ISBN","图书出版社",
  28. "封面图片"};
  29. List<Book>dataset=newArrayList<Book>();
  30. try{
  31. BufferedInputStreambis=newBufferedInputStream(
  32. newFileInputStream(file));
  33. byte[]buf=newbyte[bis.available()];
  34. while((bis.read(buf))!=-1){
  35. //将图片数据存放到缓冲数组中
  36. }
  37. dataset.add(newBook(1,"jsp","leno",300.33f,"1234567","清华出版社",
  38. buf));
  39. dataset.add(newBook(2,"java编程思想","brucl",300.33f,"1234567",
  40. "阳光出版社",buf));
  41. dataset.add(newBook(3,"DOM艺术","lenotang",300.33f,"1234567",
  42. "清华出版社",buf));
  43. dataset.add(newBook(4,"c++经典","leno",400.33f,"1234567",
  44. "清华出版社",buf));
  45. dataset.add(newBook(5,"c#入门","leno",300.33f,"1234567",
  46. "汤春秀出版社",buf));
  47. OutputStreamout=response.getOutputStream();
  48. ex.exportExcel(headers,dataset,out);
  49. out.close();
  50. System.out.println("excel导出成功!");
  51. }catch(FileNotFoundExceptione){
  52. //TODOAuto-generatedcatchblock
  53. e.printStackTrace();
  54. }catch(IOExceptione){
  55. //TODOAuto-generatedcatchblock
  56. e.printStackTrace();
  57. }
  58. }
  59. protectedvoiddoPost(HttpServletRequestrequest,
  60. HttpServletResponseresponse)throwsServletException,IOException{
  61. doGet(request,response);
  62. }
  63. }

  写完之后,如果您不是用eclipse工具生成的Servlet,千万别忘了在web.xml上注册这个Servelt。而且同样的,拷贝一张小巧的图书图片命名为book.jpg放置到当前WEB根目录的/WEB-INF/下。部署好web工程,用浏览器访问Servlet看下效果吧!是不是下载成功了。呵呵,您可以将下载到本地的excel报表用打印机打印出来,这样您就大功告成了。完事了我们就思考:我们发现,我们做的方法,不管是本地调用,还是在WEB服务器端用Servlet调用;不管是输出学生列表,还是图书列表信息,代码都几乎一样,而且这些数据我们很容器结合后台的DAO操作数据库动态获取。恩,类和方法的通用性和灵活性开始有点感觉了。好啦,祝您学习愉快!

jsp/servlet测试通过。。。

POI导出EXCEL经典实现(附带jar包)_第1张图片

poi-3.0.2-FINAL-20080204.jar下载地址:

http://download.csdn.net/source/3302564

你可能感兴趣的:(导出Excel)