转自http://blog.csdn.net/evangel_z/article/details/7332535

在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. import java.util.Date;
  2.  
  3. public class Student
  4. {
  5. private long id;
  6. private String name;
  7. private int age;
  8. private boolean sex;
  9. private Date birthday;
  10.  
  11. public Student()
  12. {
  13. }
  14.  
  15. public Student(long id, String name, int age, boolean sex, Date birthday)
  16. {
  17. this.id = id;
  18. this.name = name;
  19. this.age = age;
  20. this.sex = sex;
  21. this.birthday = birthday;
  22. }
  23.  
  24. public long getId()
  25. {
  26. return id;
  27. }
  28.  
  29. public void setId(long id)
  30. {
  31. this.id = id;
  32. }
  33.  
  34. public String getName()
  35. {
  36. return name;
  37. }
  38.  
  39. public void setName(String name)
  40. {
  41. this.name = name;
  42. }
  43.  
  44. public int getAge()
  45. {
  46. return age;
  47. }
  48.  
  49. public void setAge(int age)
  50. {
  51. this.age = age;
  52. }
  53.  
  54. public boolean getSex()
  55. {
  56. return sex;
  57. }
  58.  
  59. public void setSex(boolean sex)
  60. {
  61. this.sex = sex;
  62. }
  63.  
  64. public Date getBirthday()
  65. {
  66. return birthday;
  67. }
  68.  
  69. public void setBirthday(Date birthday)
  70. {
  71. this.birthday = birthday;
  72. }
  73.  
  74. }
  1. public class Book
  2. {
  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.  
  11. public Book()
  12. {
  13. }
  14.  
  15. public Book(int bookId, String name, String author, float price,
  16. String isbn, String pubName, byte[] preface)
  17. {
  18. this.bookId = bookId;
  19. this.name = name;
  20. this.author = author;
  21. this.price = price;
  22. this.isbn = isbn;
  23. this.pubName = pubName;
  24. this.preface = preface;
  25. }
  26.  
  27. public int getBookId()
  28. {
  29. return bookId;
  30. }
  31.  
  32. public void setBookId(int bookId)
  33. {
  34. this.bookId = bookId;
  35. }
  36.  
  37. public String getName()
  38. {
  39. return name;
  40. }
  41.  
  42. public void setName(String name)
  43. {
  44. this.name = name;
  45. }
  46.  
  47. public String getAuthor()
  48. {
  49. return author;
  50. }
  51.  
  52. public void setAuthor(String author)
  53. {
  54. this.author = author;
  55. }
  56.  
  57. public float getPrice()
  58. {
  59. return price;
  60. }
  61.  
  62. public void setPrice(float price)
  63. {
  64. this.price = price;
  65. }
  66.  
  67. public String getIsbn()
  68. {
  69. return isbn;
  70. }
  71.  
  72. public void setIsbn(String isbn)
  73. {
  74. this.isbn = isbn;
  75. }
  76.  
  77. public String getPubName()
  78. {
  79. return pubName;
  80. }
  81.  
  82. public void setPubName(String pubName)
  83. {
  84. this.pubName = pubName;
  85. }
  86.  
  87. public byte[] getPreface()
  88. {
  89. return preface;
  90. }
  91.  
  92. public void setPreface(byte[] preface)
  93. {
  94. this.preface = preface;
  95. }
  96. }

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

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

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

简单版 无excel格式样式设置  及excel下载

  1. package com.howbuy.uaa.utils;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.BufferedOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.lang.reflect.Field;
  11. import java.lang.reflect.InvocationTargetException;
  12. import java.lang.reflect.Method;
  13. import java.text.SimpleDateFormat;
  14. import java.util.Collection;
  15. import java.util.Date;
  16. import java.util.Iterator;
  17. import java.util.regex.Matcher;
  18. import java.util.regex.Pattern;
  19.  
  20. import javax.servlet.http.HttpServletResponse;
  21.  
  22. import org.apache.poi.hssf.usermodel.HSSFCell;
  23. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  24. import org.apache.poi.hssf.usermodel.HSSFFont;
  25. import org.apache.poi.hssf.usermodel.HSSFRichTextString;
  26. import org.apache.poi.hssf.usermodel.HSSFRow;
  27. import org.apache.poi.hssf.usermodel.HSSFSheet;
  28. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  29.  
  30. public class ExportExcel<T> {
  31. public void exportExcel(String title,Collection<T> dataset, OutputStream out) {
  32. exportExcel(title, null, dataset, out, "yyyy-MM-dd");
  33. }
  34.  
  35. public void exportExcel(String title,String[] headers, Collection<T> dataset,
  36. OutputStream out) {
  37. exportExcel(title, headers, dataset, out, "yyyy-MM-dd");
  38. }
  39.  
  40. @SuppressWarnings("unchecked")
  41. public void exportExcel(String title, String[] headers,Collection<T> dataset, OutputStream out, String pattern) {
  42. // 声明一个工作薄
  43. HSSFWorkbook workbook = new HSSFWorkbook();
  44. // 生成一个表格
  45. HSSFSheet sheet = workbook.createSheet(title);
  46. // 设置表格默认列宽度为15个字节
  47. sheet.setDefaultColumnWidth((short) 15);
  48. // 生成一个样式
  49. HSSFCellStyle style = workbook.createCellStyle();
  50. // 生成一个字体
  51. HSSFFont font = workbook.createFont();
  52. font.setFontHeightInPoints((short) 12);
  53. // 把字体应用到当前的样式
  54. style.setFont(font);
  55. // 产生表格标题行
  56. HSSFRow row = sheet.createRow(0);
  57. for (short i = 0; i < headers.length; i++) {
  58. HSSFCell cell = row.createCell(i);
  59. cell.setCellStyle(style);
  60. HSSFRichTextString text = new HSSFRichTextString(headers[i]);
  61. cell.setCellValue(text);
  62. }
  63. // 遍历集合数据,产生数据行
  64. Iterator<T> it = dataset.iterator();
  65. int index = 0;
  66. while (it.hasNext()) {
  67. index++;
  68. row = sheet.createRow(index);
  69. T t = (T) it.next();
  70. // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
  71. Field[] fields = t.getClass().getDeclaredFields();
  72. for (short i = 0; i < fields.length; i++) {
  73. HSSFCell cell = row.createCell(i);
  74. cell.setCellStyle(style);
  75. Field field = fields[i];
  76. String fieldName = field.getName();
  77. String getMethodName = "get"
  78. + fieldName.substring(0, 1).toUpperCase()
  79. + fieldName.substring(1);
  80. try {
  81. Class tCls = t.getClass();
  82. Method getMethod = tCls.getMethod(getMethodName,
  83. new Class[] {});
  84. Object value = getMethod.invoke(t, new Object[] {});
  85. // 判断值的类型后进行强制类型转换
  86. String textValue = null;
  87. if (value instanceof Integer) {
  88. int intValue = (Integer) value;
  89. cell.setCellValue(intValue);
  90. }
  91. else if (value instanceof Long) {
  92. long longValue = (Long) value;
  93. cell.setCellValue(longValue);
  94. }
  95. else if (value instanceof Boolean) {
  96. boolean bValue = (Boolean) value;
  97. textValue = "1";
  98. if (!bValue) {
  99. textValue = "0";
  100. }
  101. } else if (value instanceof Date) {
  102. Date date = (Date) value;
  103. SimpleDateFormat sdf = new SimpleDateFormat(pattern);
  104. textValue = sdf.format(date);
  105. } else {
  106. // 其它数据类型都当作字符串简单处理
  107. if(value == null)
  108. {
  109. textValue = "";
  110. }
  111. else {
  112. textValue = value.toString();
  113. }
  114.  
  115. }
  116.  
  117. if (textValue != null) {
  118. Pattern p = Pattern.compile("^//d+(//.//d+)?$");
  119. Matcher matcher = p.matcher(textValue);
  120. if (matcher.matches()) {
  121. // 是数字当作double处理
  122. cell.setCellValue(Double.parseDouble(textValue));
  123. } else {
  124. HSSFRichTextString richString = new HSSFRichTextString(
  125. textValue);
  126. richString.applyFont(font);
  127. cell.setCellValue(richString);
  128. }
  129. }
  130. } catch (SecurityException e) {
  131. e.printStackTrace();
  132. } catch (NoSuchMethodException e) {
  133. e.printStackTrace();
  134. } catch (IllegalArgumentException e) {
  135. e.printStackTrace();
  136. } catch (IllegalAccessException e) {
  137. e.printStackTrace();
  138. } catch (InvocationTargetException e) {
  139. e.printStackTrace();
  140. } finally {
  141. // 清理资源
  142. }
  143. }
  144.  
  145. }
  146. try {
  147. workbook.write(out);
  148. } catch (IOException e) {
  149. e.printStackTrace();
  150. }
  151. }
  152.  
  153. public void downloadExcel(String path, HttpServletResponse response) {
  154. try {
  155. // path是指欲下载的文件的路径。
  156. File file = new File(path);
  157. String name = file.getName();
  158. // 取得文件名。
  159. String filename = java.net.URLEncoder.encode(name,"utf-8");
  160. // 清空response
  161. response.reset();
  162. // 设置response的Header
  163. response.addHeader("Content-Disposition", "attachment;filename="
  164. + new String(filename.getBytes()));
  165. response.addHeader("Content-Length", "" + file.length());
  166. OutputStream toClient = new BufferedOutputStream(
  167. response.getOutputStream());
  168. response.setContentType("application/ms-excel;charset=gb2312");
  169. // 以流的形式下载文件。
  170. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  171. byte[] buffer = new byte[fis.available()];
  172. fis.read(buffer);
  173. fis.close();
  174. toClient.write(buffer);
  175. toClient.flush();
  176. toClient.close();
  177. } catch (IOException ex) {
  178. ex.printStackTrace();
  179. }
  180. }
  181. }

Java POI 导出EXCEL经典实现 Java导出Excel的更多相关文章

  1. Java POI 导出EXCEL经典实现 Java导出Excel弹出下载框(转载)

    https://blog.csdn.net/evangel_z/article/details/7332535

  2. JAVA POI 应用系列(2)--读取Excel

    添加maven依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi< ...

  3. JAVA POI 应用系列(1)--生成Excel

    POI简介(官网:http://poi.apache.org/)     Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office ...

  4. JAVA中去掉空格经典整理

    JAVA中去掉空格经典整理 JAVA中去掉空格          1. String.trim() --------------trim()是去掉首尾空格           2.str.replac ...

  5. 重构:以Java POI 导出EXCEL为例

    重构 开头先抛出几个问题吧,这几个问题也是<重构:改善既有代码的设计>这本书第2章的问题. 什么是重构? 为什么要重构? 什么时候要重构? 接下来就从这几个问题出发,通过这几个问题来系统的 ...

  6. java POI excel 导出复合样式(一个单元格两个字体)

    前言:java poi 导出 excel 时,需要设置一个单元格有多个字体样式,有点类似于富文本. 想要达到的效果(一个单元格里): 我使用的 poi 版本是 <dependency> & ...

  7. java使用POI操作excel文件,实现批量导出,和导入

    一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Exc ...

  8. java POI导出Excel文件数据库的数据

    在web开发中,有一个经典的功能,就是数据的导入导出.特别是数据的导出,在生产管理或者财务系统中用的非常普遍,因为这些系统经常要做一些报表打印的工作.这里我简单实现导出Excel文件. POI jar ...

  9. java解决poi导出excel文字水印,导出excel不可操作问题

    首先需求是用户提出导出excel数据需使用水印备注其用途: 其实就是在导出excel的同时带有自定义文字水印的导出. 那么我们首先想到的肯定是以一个什么样的思路去解决该问题,首先查找poi导出exce ...

随机推荐

  1. angular js 表单验证

    <!doctype html> <html ng-app="myapp"> <head> <meta charset="UTF- ...

  2. Java整型与字符串相互转换(转)

    1如何将字串 String 转换成整数 int? A. 有两个方法: 1). int i = Integer.parseInt([String]); 或 i = Integer.parseInt([S ...

  3. Qt编写串口通信程序全程图文解说

    (说明:我们的编程环境是windows xp下,在Qt Creator中进行,假设在Linux下或直接用源代码编写,程序稍有不同,请自己修改.) 在Qt中并没有特定的串口控制类,如今大部分人使用的是第 ...

  4. mybatis01

    mybatis是一个java持久层框架,java中操作关系型 数据库用的是jdbc,mybatis是对jdbc的一个封装. jdk1..0_72 eclipse:eclipse-3.7-indigo ...

  5. iOS AFNetWorking源码详解(一)

    来源:Yuzeyang 链接:http://zeeyang.com/2016/02/21/AFNetWorking-one/ 首先来介绍下AFNetWorking,官方介绍如下: AFNetworki ...

  6. hdu2091JAVA

    空心三角形 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  7. Java基础知识强化之IO流笔记28:BufferedOutputStream / BufferedInputStream(字节缓冲区流) 之BufferedOutputStream写出数据

    1. BufferedOutputStream / BufferedInputStream(字节缓冲区流)的概述 通过定义数组的方式确实比以前一次读取一个字节的方式快很多,所以,看来有一个缓冲区还是非 ...

  8. Bootstarp--全局CSS样式之表格

    表格在实际开发中可以说是非常常见的,但是有很多人不喜欢使用表格,但个人觉得在简单的界面布局中使用表格还是很简单的.毕竟人家给了表格这元素,而你却不去使用,貌似有点不解风情. 下面简单介绍Bootstr ...

  9. Handler 原理分析和使用(二)

    在上篇 Handler 原理分析和使用(一)中,介绍了一个使用Handler的一个简单而又常见的例子,这里还有一个例子,当然和上一篇的例子截然不同,也是比较常见的,实例如下. import andro ...

  10. Android - 向服务器发送数据(GET).

    在此,使用HTTP协议,通过GET请求,向服务器发送请求,这种方式适合于数据量小,数据安全性要求不高的情况下. 一,服务器端,使用Servlet. 在服务器端,定义一个HttpServlet的子类,以 ...