POI导出EXCEL经典实现

1.Apache POI简介

Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能。 .NET的开发人员则可以利用NPOI (POI for .NET) 来存取 POI 的功能。

2.POI结构

HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF - 提供读写Microsoft Word DOC格式档案的功能。
HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。

3.Busy Developers' Guide to HSSF and XSSF Features

官方网站:http://poi.apache.org/spreadsheet/quick-guide.html

参考博客:http://langhua9527.iteye.com/blog/388005

4.参考实例

。现在主流的操作Excel文件的开源工具有很多,用得比较多的就是Apache的POI及JExcelAPI。这里我们用Apache POI!我们先去Apache的大本营下载POI的jar包:http://poi.apache.org/ ,我这里使用的是3.0.2版本。
  1. package org.leno.export.util;
  2. import java.util.Date;
  3. public class Student {
  4. private long id;
  5. private String name;
  6. private int age;
  7. private boolean sex;
  8. private Date birthday;
  9. public Student() {
  10. super();
  11. // TODO Auto-generated constructor stub
  12. }
  13. public Student(long id, String name, int age, boolean sex, Date birthday) {
  14. super();
  15. this.id = id;
  16. this.name = name;
  17. this.age = age;
  18. this.sex = sex;
  19. this.birthday = birthday;
  20. }
  21. public long getId() {
  22. return id;
  23. }
  24. public void setId(long id) {
  25. this.id = id;
  26. }
  27. public String getName() {
  28. return name;
  29. }
  30. public void setName(String name) {
  31. this.name = name;
  32. }
  33. public int getAge() {
  34. return age;
  35. }
  36. public void setAge(int age) {
  37. this.age = age;
  38. }
  39. public boolean getSex() {
  40. return sex;
  41. }
  42. public void setSex(boolean sex) {
  43. this.sex = sex;
  44. }
  45. public Date getBirthday() {
  46. return birthday;
  47. }
  48. public void setBirthday(Date birthday) {
  49. this.birthday = birthday;
  50. }
  51. }
  1. package org.leno.export.util;
  2. public class Book {
  3. private int bookId;
  4. private String name;
  5. private String author;
  6. private float price;
  7. private String isbn;
  8. private String pubName;
  9. private byte[] preface;
  10. public Book() {
  11. super();
  12. }
  13. public Book(int bookId, String name, String author, float price,
  14. String isbn, String pubName, 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. public int getBookId() {
  25. return bookId;
  26. }
  27. public void setBookId(int bookId) {
  28. this.bookId = bookId;
  29. }
  30. public String getName() {
  31. return name;
  32. }
  33. public void setName(String name) {
  34. this.name = name;
  35. }
  36. public String getAuthor() {
  37. return author;
  38. }
  39. public void setAuthor(String author) {
  40. this.author = author;
  41. }
  42. public float getPrice() {
  43. return price;
  44. }
  45. public void setPrice(float price) {
  46. this.price = price;
  47. }
  48. public String getIsbn() {
  49. return isbn;
  50. }
  51. public void setIsbn(String isbn) {
  52. this.isbn = isbn;
  53. }
  54. public String getPubName() {
  55. return pubName;
  56. }
  57. public void setPubName(String pubName) {
  58. this.pubName = pubName;
  59. }
  60. public byte[] getPreface() {
  61. return preface;
  62. }
  63. public void setPreface(byte[] preface) {
  64. this.preface = preface;
  65. }
  66. }
  1. package org.leno.export.util;
  2. import java.io.*;
  3. import java.lang.reflect.*;
  4. import java.util.*;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. import java.text.SimpleDateFormat;
  8. import javax.swing.JOptionPane;
  9. import org.apache.poi.hssf.usermodel.*;
  10. import org.apache.poi.hssf.util.HSSFColor;
  11. /**
  12. * 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!
  13. *
  14. * @author leno
  15. * @version v1.0
  16. * @param <T>
  17. * 应用泛型,代表任意一个符合javabean风格的类
  18. * 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
  19. * byte[]表jpg格式的图片数据
  20. */
  21. public class ExportExcel <T> {
  22. public void exportExcel(Collection <T> dataset, OutputStream out) {
  23. exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");
  24. }
  25. public void exportExcel(String[] headers, Collection <T> dataset,
  26. OutputStream out) {
  27. exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");
  28. }
  29. public void exportExcel(String[] headers, Collection <T> dataset,
  30. OutputStream out, String pattern) {
  31. exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern);
  32. }
  33. /**
  34. * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
  35. *
  36. * @param title
  37. * 表格标题名
  38. * @param headers
  39. * 表格属性列名数组
  40. * @param dataset
  41. * 需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
  42. * javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
  43. * @param out
  44. * 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
  45. * @param pattern
  46. * 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
  47. */
  48. @SuppressWarnings("unchecked")
  49. public void exportExcel(String title, String[] headers,
  50. Collection <T> dataset, OutputStream out, String pattern) {
  51. // 声明一个工作薄
  52. HSSFWorkbook workbook = new HSSFWorkbook();
  53. // 生成一个表格
  54. HSSFSheet sheet = workbook.createSheet(title);
  55. // 设置表格默认列宽度为15个字节
  56. sheet.setDefaultColumnWidth((short) 15);
  57. // 生成一个样式
  58. HSSFCellStyle style = workbook.createCellStyle();
  59. // 设置这些样式
  60. style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
  61. style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  62. style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  63. style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  64. style.setBorderRight(HSSFCellStyle.BORDER_THIN);
  65. style.setBorderTop(HSSFCellStyle.BORDER_THIN);
  66. style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  67. // 生成一个字体
  68. HSSFFont font = workbook.createFont();
  69. font.setColor(HSSFColor.VIOLET.index);
  70. font.setFontHeightInPoints((short) 12);
  71. font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  72. // 把字体应用到当前的样式
  73. style.setFont(font);
  74. // 生成并设置另一个样式
  75. HSSFCellStyle style2 = workbook.createCellStyle();
  76. style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
  77. style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  78. style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  79. style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  80. style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
  81. style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
  82. style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  83. style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  84. // 生成另一个字体
  85. HSSFFont font2 = workbook.createFont();
  86. font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  87. // 把字体应用到当前的样式
  88. style2.setFont(font2);
  89. // 声明一个画图的顶级管理器
  90. HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
  91. // 定义注释的大小和位置,详见文档
  92. HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
  93. 0, 0, 0, (short) 4, 2, (short) 6, 5));
  94. // 设置注释内容
  95. comment.setString(new HSSFRichTextString("可以在POI中添加注释!"));
  96. // 设置注释作者,当鼠标移动到单元格上是可以在状态栏中看到该内容.
  97. comment.setAuthor("leno");
  98. // 产生表格标题行
  99. HSSFRow row = sheet.createRow(0);
  100. for (short i = 0; i < headers.length; i++) {
  101. HSSFCell cell = row.createCell(i);
  102. cell.setCellStyle(style);
  103. HSSFRichTextString text = new HSSFRichTextString(headers[i]);
  104. cell.setCellValue(text);
  105. }
  106. // 遍历集合数据,产生数据行
  107. Iterator<T> it = dataset.iterator();
  108. int index = 0;
  109. while (it.hasNext()) {
  110. index++;
  111. row = sheet.createRow(index);
  112. T t = (T) it.next();
  113. // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
  114. Field[] fields = t.getClass().getDeclaredFields();
  115. for (short i = 0; i < fields.length; i++) {
  116. HSSFCell cell = row.createCell(i);
  117. cell.setCellStyle(style2);
  118. Field field = fields[i];
  119. String fieldName = field.getName();
  120. String getMethodName = "get"
  121. + fieldName.substring(0, 1).toUpperCase()
  122. + fieldName.substring(1);
  123. try {
  124. Class tCls = t.getClass();
  125. Method getMethod = tCls.getMethod(getMethodName,
  126. new Class[] {});
  127. Object value = getMethod.invoke(t, new Object[] {});
  128. // 判断值的类型后进行强制类型转换
  129. String textValue = null;
  130. // if (value instanceof Integer) {
  131. // int intValue = (Integer) value;
  132. // cell.setCellValue(intValue);
  133. // } else if (value instanceof Float) {
  134. // float fValue = (Float) value;
  135. // textValue = new HSSFRichTextString(
  136. // String.valueOf(fValue));
  137. // cell.setCellValue(textValue);
  138. // } else if (value instanceof Double) {
  139. // double dValue = (Double) value;
  140. // textValue = new HSSFRichTextString(
  141. // String.valueOf(dValue));
  142. // cell.setCellValue(textValue);
  143. // } else if (value instanceof Long) {
  144. // long longValue = (Long) value;
  145. // cell.setCellValue(longValue);
  146. // }
  147. if (value instanceof Boolean) {
  148. boolean bValue = (Boolean) value;
  149. textValue = "男";
  150. if (!bValue) {
  151. textValue = "女";
  152. }
  153. } else if (value instanceof Date) {
  154. Date date = (Date) value;
  155. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  156. textValue = sdf.format(date);
  157. } else if (value instanceof byte[]) {
  158. // 有图片时,设置行高为60px;
  159. row.setHeightInPoints(60);
  160. // 设置图片所在列宽度为80px,注意这里单位的一个换算
  161. sheet.setColumnWidth(i, (short) (35.7 * 80));
  162. // sheet.autoSizeColumn(i);
  163. byte[] bsValue = (byte[]) value;
  164. HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
  165. 1023, 255, (short) 6, index, (short) 6, index);
  166. anchor.setAnchorType(2);
  167. patriarch.createPicture(anchor, workbook.addPicture(
  168. bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
  169. } else {
  170. // 其它数据类型都当作字符串简单处理
  171. textValue = value.toString();
  172. }
  173. // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
  174. if (textValue != null) {
  175. Pattern p = Pattern.compile("^//d+(//.//d+)?{1}quot;);
  176. Matcher matcher = p.matcher(textValue);
  177. if (matcher.matches()) {
  178. // 是数字当作double处理
  179. cell.setCellValue(Double.parseDouble(textValue));
  180. } else {
  181. HSSFRichTextString richString = new HSSFRichTextString(
  182. textValue);
  183. HSSFFont font3 = workbook.createFont();
  184. font3.setColor(HSSFColor.BLUE.index);
  185. richString.applyFont(font3);
  186. cell.setCellValue(richString);
  187. }
  188. }
  189. } catch (SecurityException e) {
  190. // TODO Auto-generated catch block
  191. e.printStackTrace();
  192. } catch (NoSuchMethodException e) {
  193. // TODO Auto-generated catch block
  194. e.printStackTrace();
  195. } catch (IllegalArgumentException e) {
  196. // TODO Auto-generated catch block
  197. e.printStackTrace();
  198. } catch (IllegalAccessException e) {
  199. // TODO Auto-generated catch block
  200. e.printStackTrace();
  201. } catch (InvocationTargetException e) {
  202. // TODO Auto-generated catch block
  203. e.printStackTrace();
  204. } finally {
  205. // 清理资源
  206. }
  207. }
  208. }
  209. try {
  210. workbook.write(out);
  211. } catch (IOException e) {
  212. // TODO Auto-generated catch block
  213. e.printStackTrace();
  214. }
  215. }
  216. public static void main(String[] args) {
  217. // 测试学生
  218. ExportExcel<Student> ex = new ExportExcel <Student>();
  219. String[] headers = { "学号", "姓名", "年龄", "性别", "出生日期" };
  220. List <Student> dataset = new ArrayList <Student>();
  221. dataset.add(new Student(10000001, "张三", 20, true, new Date()));
  222. dataset.add(new Student(20000002, "李四", 24, false, new Date()));
  223. dataset.add(new Student(30000003, "王五", 22, true, new Date()));
  224. // 测试图书
  225. ExportExcel <Book> ex2 = new ExportExcel <Book>();
  226. String[] headers2 = { "图书编号", "图书名称", "图书作者", "图书价格", "图书ISBN",
  227. "图书出版社", "封面图片" };
  228. List <Book> dataset2 = new ArrayList <Book>();
  229. try {
  230. BufferedInputStream bis = new BufferedInputStream(
  231. new FileInputStream("book.jpg"));
  232. byte[] buf = new byte[bis.available()];
  233. while ((bis.read(buf)) != -1) {
  234. //
  235. }
  236. dataset2.add(new Book(1, "jsp", "leno", 300.33f, "1234567",
  237. "清华出版社", buf));
  238. dataset2.add(new Book(2, "java编程思想", "brucl", 300.33f, "1234567",
  239. "阳光出版社", buf));
  240. dataset2.add(new Book(3, "DOM艺术", "lenotang", 300.33f, "1234567",
  241. "清华出版社", buf));
  242. dataset2.add(new Book(4, "c++经典", "leno", 400.33f, "1234567",
  243. "清华出版社", buf));
  244. dataset2.add(new Book(5, "c#入门", "leno", 300.33f, "1234567",
  245. "汤春秀出版社", buf));
  246. OutputStream out = new FileOutputStream("E://a.xls");
  247. OutputStream out2 = new FileOutputStream("E://b.xls");
  248. ex.exportExcel(headers, dataset, out);
  249. ex2.exportExcel(headers2, dataset2, out2);
  250. out.close();
  251. JOptionPane.showMessageDialog(null, "导出成功!");
  252. System.out.println("excel导出成功!");
  253. } catch (FileNotFoundException e) {
  254. // TODO Auto-generated catch block
  255. e.printStackTrace();
  256. } catch (IOException e) {
  257. // TODO Auto-generated catch block
  258. e.printStackTrace();
  259. }
  260. }
  261. }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值