Java之——导出Excel通用工具类

转载请注明出处:https://blog.csdn.net/l1028386804/article/details/79659605
//本次做了相应调整,增加需要导出的行,不需要的行无需生成Excel

一、概述

相信大家在工作过程中,都会遇到这样一个需求,就是将相关的数据列表导出成excel,那么,有没有通用的导出方式呢,这里,就带着大家一起来用Java实现一个通用的导出Excel的工具。

二、项目实现

1、构建pom.xml

我们的工程是利用Maven来构建的,项目具体搭建过程大家可以参见网上其他资料,这里我们仅给出最核心的Maven配置

[html]  view plain  copy
  1. <dependency>  
  2.     <groupId>org.apache.poi</groupId>  
  3.     <artifactId>poi-scratchpad</artifactId>  
  4.     <version>3.11-beta2</version>  
  5. </dependency>  
  6. <dependency>  
  7.     <groupId>org.apache.poi</groupId>  
  8.     <artifactId>poi-ooxml</artifactId>  
  9.     <version>3.11-beta2</version>  
  10. </dependency>  

2、编写ExportExcelUtil类

这个类使我们整个工具的核心,它实现了Excel文件的导出功能,具体代码如下:

[java]  view plain  copy
  1. package com.lyz.utils.excel.poi;  
  2. import java.io.IOException;  
  3. import java.io.OutputStream;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Collection;  
  9. import java.util.Date;  
  10. import java.util.Iterator;  
  11. import java.util.regex.Matcher;  
  12. import java.util.regex.Pattern;  
  13.   
  14. import org.apache.commons.lang3.StringUtils;  
  15. import org.apache.poi.hssf.usermodel.HSSFCell;  
  16. import org.apache.poi.hssf.usermodel.HSSFCellStyle;  
  17. import org.apache.poi.hssf.usermodel.HSSFFont;  
  18. import org.apache.poi.hssf.usermodel.HSSFRichTextString;  
  19. import org.apache.poi.hssf.usermodel.HSSFRow;  
  20. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  21. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  22. import org.apache.poi.hssf.util.HSSFColor;  
  23. import org.apache.poi.xssf.usermodel.XSSFCell;  
  24. import org.apache.poi.xssf.usermodel.XSSFCellStyle;  
  25. import org.apache.poi.xssf.usermodel.XSSFColor;  
  26. import org.apache.poi.xssf.usermodel.XSSFFont;  
  27. import org.apache.poi.xssf.usermodel.XSSFRichTextString;  
  28. import org.apache.poi.xssf.usermodel.XSSFRow;  
  29. import org.apache.poi.xssf.usermodel.XSSFSheet;  
  30. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  31.   
  32.   
  33. /** 
  34.  * 导出Excel 
  35.  * @author liuyazhuang 
  36.  * 
  37.  * @param <T> 
  38.  */  
  39. public class ExportExcelUtil<T>{  
  40.       
  41.     // 2007 版本以上 最大支持1048576行  
  42.     public  final static String  EXCEl_FILE_2007 = "2007";  
  43.     // 2003 版本 最大支持65536 行  
  44.     public  final static String  EXCEL_FILE_2003 = "2003";  
  45.       
  46.     /** 
  47.      * <p> 
  48.      * 导出无头部标题行Excel <br> 
  49.      * 时间格式默认:yyyy-MM-dd hh:mm:ss <br> 
  50.      * </p> 
  51.      *  
  52.      * @param title 表格标题 
  53.      * @param dataset 数据集合 
  54.      * @param out 输出流 
  55.      * @param version 2003 或者 2007,不传时默认生成2003版本 
  56.      */  
  57.     public void exportExcel(String title, String[] columns, Collection<T> dataset, OutputStream out, String version) {  
  58.         if(StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())){  
  59.             exportExcel2003(title, null, columns, dataset, out, "yyyy-MM-dd hh:mm:ss");  
  60.         }else{  
  61.             exportExcel2007(title, null, columns, dataset, out, "yyyy-MM-dd hh:mm:ss");  
  62.         }  
  63.     }  
  64.   
  65.     /** 
  66.      * <p> 
  67.      * 导出带有头部标题行的Excel <br> 
  68.      * 时间格式默认:yyyy-MM-dd hh:mm:ss <br> 
  69.      * </p> 
  70.      *  
  71.      * @param title 表格标题 
  72.      * @param headers 头部标题集合 
  73.      * @param dataset 数据集合 
  74.      * @param out 输出流 
  75.      * @param version 2003 或者 2007,不传时默认生成2003版本 
  76.      */  
  77.     public void exportExcel(String title,String[] headers, String[] columns, Collection<T> dataset, OutputStream out,String version) {  
  78.         if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){  
  79.             exportExcel2003(title, headers, columns, dataset, out, "yyyy-MM-dd hh:mm:ss");  
  80.         }else{  
  81.             exportExcel2007(title, headers, columns, dataset, out, "yyyy-MM-dd hh:mm:ss");  
  82.         }  
  83.     }  
  84.   
  85.     /** 
  86.      * <p> 
  87.      * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br> 
  88.      * 此版本生成2007以上版本的文件 (文件后缀:xlsx) 
  89.      * </p> 
  90.      *  
  91.      * @param title 
  92.      *            表格标题名 
  93.      * @param headers 
  94.      *            表格头部标题集合 
  95.      * @param dataset 
  96.      *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 
  97.      *            JavaBean属性的数据类型有基本数据类型及String,Date 
  98.      * @param out 
  99.      *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 
  100.      * @param pattern 
  101.      *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" 
  102.      */  
  103.     @SuppressWarnings({ "unchecked""rawtypes" })  
  104.     public void exportExcel2007(String title, String[] headers, String[] columns, Collection<T> dataset, OutputStream out, String pattern) {  
  105.         // 声明一个工作薄  
  106.         XSSFWorkbook workbook = new XSSFWorkbook();  
  107.         // 生成一个表格  
  108.         XSSFSheet sheet = workbook.createSheet(title);  
  109.         // 设置表格默认列宽度为15个字节  
  110.         sheet.setDefaultColumnWidth(20);  
  111.         // 生成一个样式  
  112.         XSSFCellStyle style = workbook.createCellStyle();  
  113.         // 设置这些样式  
  114.         style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));  
  115.         style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);  
  116.         style.setBorderBottom(XSSFCellStyle.BORDER_THIN);  
  117.         style.setBorderLeft(XSSFCellStyle.BORDER_THIN);  
  118.         style.setBorderRight(XSSFCellStyle.BORDER_THIN);  
  119.         style.setBorderTop(XSSFCellStyle.BORDER_THIN);  
  120.         style.setAlignment(XSSFCellStyle.ALIGN_CENTER);  
  121.         // 生成一个字体  
  122.         XSSFFont font = workbook.createFont();  
  123.         font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);  
  124.         font.setFontName("宋体");   
  125.         font.setColor(new XSSFColor(java.awt.Color.BLACK));  
  126.         font.setFontHeightInPoints((short11);  
  127.         // 把字体应用到当前的样式  
  128.         style.setFont(font);  
  129.         // 生成并设置另一个样式  
  130.         XSSFCellStyle style2 = workbook.createCellStyle();  
  131.         style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));  
  132.         style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);  
  133.         style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);  
  134.         style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);  
  135.         style2.setBorderRight(XSSFCellStyle.BORDER_THIN);  
  136.         style2.setBorderTop(XSSFCellStyle.BORDER_THIN);  
  137.         style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);  
  138.         style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);  
  139.         // 生成另一个字体  
  140.         XSSFFont font2 = workbook.createFont();  
  141.         font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);  
  142.         // 把字体应用到当前的样式  
  143.         style2.setFont(font2);  
  144.   
  145.         // 产生表格标题行  
  146.         XSSFRow row = sheet.createRow(0);  
  147.         XSSFCell cellHeader;  
  148.         for (int i = 0; i < headers.length; i++) {  
  149.             cellHeader = row.createCell(i);  
  150.             cellHeader.setCellStyle(style);  
  151.             cellHeader.setCellValue(new XSSFRichTextString(headers[i]));  
  152.         }  
  153.   
  154.         // 遍历集合数据,产生数据行  
  155.         Iterator<T> it = dataset.iterator();  
  156.         int index = 0;  
  157.         T t;  
  158.         Field[] fields;  
  159.         Field field;  
  160.         XSSFRichTextString richString;  
  161.         Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
  162.         Matcher matcher;  
  163.         String fieldName;  
  164.         String getMethodName;  
  165.         XSSFCell cell;  
  166.         Class tCls;  
  167.         Method getMethod;  
  168.         Object value;  
  169.         String textValue;  
  170.         SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  171.         while (it.hasNext()) {  
  172.             index++;  
  173.             row = sheet.createRow(index);  
  174.             t = (T) it.next();  
  175.             // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值  
  176.             fields = t.getClass().getDeclaredFields();
                int total = 0; 
     //修改之处
  177.             for (int i = 0; i < fields.length; i++) {
                    boolean flag = Arrays.asList(columns).contains(fields[i].getName());     //修改之处
                    if(flag){                 
  178.                 cell = row.createCell(total);  //修改之处
                    total ++;                     //修改之处
  179.                 cell.setCellStyle(style2);  
  180.                 field = fields[i];  
  181.                 fieldName = field.getName();  
  182.                 getMethodName = "get" + fieldName.substring(01).toUpperCase()  
  183.                         + fieldName.substring(1);  
  184.                 try {  
  185.                     tCls = t.getClass();  
  186.                     getMethod = tCls.getMethod(getMethodName, new Class[] {});  
  187.                     value = getMethod.invoke(t, new Object[] {});  
  188.                     // 判断值的类型后进行强制类型转换  
  189.                     textValue = null;  
  190.                     if (value instanceof Integer) {  
  191.                         cell.setCellValue((Integer) value);  
  192.                     } else if (value instanceof Float) {  
  193.                         textValue = String.valueOf((Float) value);  
  194.                         cell.setCellValue(textValue);  
  195.                     } else if (value instanceof Double) {  
  196.                         textValue = String.valueOf((Double) value);  
  197.                         cell.setCellValue(textValue);  
  198.                     } else if (value instanceof Long) {  
  199.                         cell.setCellValue((Long) value);  
  200.                     }  
  201.                     if (value instanceof Boolean) {  
  202.                         textValue = "是";  
  203.                         if (!(Boolean) value) {  
  204.                             textValue = "否";  
  205.                         }  
  206.                     } else if (value instanceof Date) {  
  207.                         textValue = sdf.format((Date) value);  
  208.                     } else {  
  209.                         // 其它数据类型都当作字符串简单处理  
  210.                         if (value != null) {  
  211.                             textValue = value.toString();  
  212.                         }  
  213.                     }  
  214.                     if (textValue != null) {  
  215.                         matcher = p.matcher(textValue);  
  216.                         if (matcher.matches()) {  
  217.                             // 是数字当作double处理  
  218.                             cell.setCellValue(Double.parseDouble(textValue));  
  219.                         } else {  
  220.                             richString = new XSSFRichTextString(textValue);  
  221.                             cell.setCellValue(richString);  
  222.                         }  
  223.                     }  
  224.                 } catch (SecurityException e) {  
  225.                     e.printStackTrace();  
  226.                 } catch (NoSuchMethodException e) {  
  227.                     e.printStackTrace();  
  228.                 } catch (IllegalArgumentException e) {  
  229.                     e.printStackTrace();  
  230.                 } catch (IllegalAccessException e) {  
  231.                     e.printStackTrace();  
  232.                 } catch (InvocationTargetException e) {  
  233.                     e.printStackTrace();  
  234.                 } finally {  
  235.                     // 清理资源  
  236.                 }  
  237.             } 
             } 
  238.         }  
  239.         try {  
  240.             workbook.write(out);  
  241.         } catch (IOException e) {  
  242.             e.printStackTrace();  
  243.         }  
  244.     }  
  245.       
  246.       
  247.       
  248.     /** 
  249.      * <p> 
  250.      * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br> 
  251.      * 此方法生成2003版本的excel,文件名后缀:xls <br> 
  252.      * </p> 
  253.      *  
  254.      * @param title 
  255.      *            表格标题名 
  256.      * @param headers 
  257.      *            表格头部标题集合 
  258.      * @param dataset 
  259.      *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 
  260.      *            JavaBean属性的数据类型有基本数据类型及String,Date 
  261.      * @param out 
  262.      *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 
  263.      * @param pattern 
  264.      *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" 
  265.      */  
  266.     @SuppressWarnings({ "unchecked""rawtypes" })  
  267.     public void exportExcel2003(String title, String[] headers, String[] columns,       Collection<T> dataset, OutputStream out, String pattern) {  
  268.         // 声明一个工作薄  
  269.         HSSFWorkbook workbook = new HSSFWorkbook();  
  270.         // 生成一个表格  
  271.         HSSFSheet sheet = workbook.createSheet(title);  
  272.         // 设置表格默认列宽度为15个字节  
  273.         sheet.setDefaultColumnWidth(20);  
  274.         // 生成一个样式  
  275.         HSSFCellStyle style = workbook.createCellStyle();  
  276.         // 设置这些样式  
  277.         style.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);  
  278.         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  279.         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  280.         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  281.         style.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  282.         style.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  283.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  284.         // 生成一个字体  
  285.         HSSFFont font = workbook.createFont();  
  286.         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  
  287.         font.setFontName("宋体");   
  288.         font.setColor(HSSFColor.WHITE.index);  
  289.         font.setFontHeightInPoints((short11);  
  290.         // 把字体应用到当前的样式  
  291.         style.setFont(font);  
  292.         // 生成并设置另一个样式  
  293.         HSSFCellStyle style2 = workbook.createCellStyle();  
  294.         style2.setFillForegroundColor(HSSFColor.WHITE.index);  
  295.         style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  
  296.         style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);  
  297.         style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);  
  298.         style2.setBorderRight(HSSFCellStyle.BORDER_THIN);  
  299.         style2.setBorderTop(HSSFCellStyle.BORDER_THIN);  
  300.         style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);  
  301.         style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
  302.         // 生成另一个字体  
  303.         HSSFFont font2 = workbook.createFont();  
  304.         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);  
  305.         // 把字体应用到当前的样式  
  306.         style2.setFont(font2);  
  307.   
  308.         // 产生表格标题行  
  309.         HSSFRow row = sheet.createRow(0);  
  310.         HSSFCell cellHeader;  
  311.         for (int i = 0; i < headers.length; i++) {  
  312.             cellHeader = row.createCell(i);  
  313.             cellHeader.setCellStyle(style);  
  314.             cellHeader.setCellValue(new HSSFRichTextString(headers[i]));  
  315.         }  
  316.   
  317.         // 遍历集合数据,产生数据行  
  318.         Iterator<T> it = dataset.iterator();  
  319.         int index = 0;  
  320.         T t;  
  321.         Field[] fields;  
  322.         Field field;  
  323.         HSSFRichTextString richString;  
  324.         Pattern p = Pattern.compile("^//d+(//.//d+)?$");  
  325.         Matcher matcher;  
  326.         String fieldName;  
  327.         String getMethodName;  
  328.         HSSFCell cell;  
  329.         Class tCls;  
  330.         Method getMethod;  
  331.         Object value;  
  332.         String textValue;  
  333.         SimpleDateFormat sdf = new SimpleDateFormat(pattern);  
  334.         while (it.hasNext()) {  
  335.             index++;  
  336.             row = sheet.createRow(index);  
  337.             t = (T) it.next();  
  338.             // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值  
  339.             fields = t.getClass().getDeclaredFields();  
                int total = 0;                                 
    //修改之处
  340.             for (int i = 0; i < fields.length; i++) { 
                    boolean flag = Arrays.asList(columns).contains(fields[i].getName());     //修改之处
                    if(flag){       
  341.                 cell = row.createCell(total);   //修改之处
                    total ++;                     
    //修改之处  
  342.                 cell.setCellStyle(style2);  
  343.                 field = fields[i];  
  344.                 fieldName = field.getName();  
  345.                 getMethodName = "get" + fieldName.substring(01).toUpperCase()  
  346.                         + fieldName.substring(1);  
  347.                 try {  
  348.                     tCls = t.getClass();  
  349.                     getMethod = tCls.getMethod(getMethodName, new Class[] {});  
  350.                     value = getMethod.invoke(t, new Object[] {});  
  351.                     // 判断值的类型后进行强制类型转换  
  352.                     textValue = null;  
  353.                     if (value instanceof Integer) {  
  354.                         cell.setCellValue((Integer) value);  
  355.                     } else if (value instanceof Float) {  
  356.                         textValue = String.valueOf((Float) value);  
  357.                         cell.setCellValue(textValue);  
  358.                     } else if (value instanceof Double) {  
  359.                         textValue = String.valueOf((Double) value);  
  360.                         cell.setCellValue(textValue);  
  361.                     } else if (value instanceof Long) {  
  362.                         cell.setCellValue((Long) value);  
  363.                     }  
  364.                     if (value instanceof Boolean) {  
  365.                         textValue = "是";  
  366.                         if (!(Boolean) value) {  
  367.                             textValue = "否";  
  368.                         }  
  369.                     } else if (value instanceof Date) {  
  370.                         textValue = sdf.format((Date) value);  
  371.                     } else {  
  372.                         // 其它数据类型都当作字符串简单处理  
  373.                         if (value != null) {  
  374.                             textValue = value.toString();  
  375.                         }  
  376.                     }  
  377.                     if (textValue != null) {  
  378.                         matcher = p.matcher(textValue);  
  379.                         if (matcher.matches()) {  
  380.                             // 是数字当作double处理  
  381.                             cell.setCellValue(Double.parseDouble(textValue));  
  382.                         } else {  
  383.                             richString = new HSSFRichTextString(textValue);  
  384.                             cell.setCellValue(richString);  
  385.                         }  
  386.                     }  
  387.                 } catch (SecurityException e) {  
  388.                     e.printStackTrace();  
  389.                 } catch (NoSuchMethodException e) {  
  390.                     e.printStackTrace();  
  391.                 } catch (IllegalArgumentException e) {  
  392.                     e.printStackTrace();  
  393.                 } catch (IllegalAccessException e) {  
  394.                     e.printStackTrace();  
  395.                 } catch (InvocationTargetException e) {  
  396.                     e.printStackTrace();  
  397.                 } finally {  
  398.                     // 清理资源  
  399.                 }  
  400.             } 
               }  
  401.         }  
  402.         try {  
  403.             workbook.write(out);  
  404.         } catch (IOException e) {  
  405.             e.printStackTrace();  
  406.         }  
  407.     }  
  408. }  

为了演示导出功能,这里我们创建了一个Student学生类。

3、创建Student类

[java]  view plain  copy
  1. package com.lyz.utils.excel.poi;  
  2.   
  3. /** 
  4.  * 例子JavaBean 
  5.  * @author liuyazhuang 
  6.  * 
  7.  */  
  8. public class Student {  
  9.     private int id;  
  10.     private String name;  
  11.     private String sex;  
  12.   
  13.     public Student(int id, String name, String sex) {  
  14.         this.id = id;  
  15.         this.name = name;  
  16.         this.sex = sex;  
  17.     }  
  18.   
  19.     public int getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(int id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.   
  31.     public void setName(String name) {  
  32.         this.name = name;  
  33.     }  
  34.   
  35.     public String getSex() {  
  36.         return sex;  
  37.     }  
  38.   
  39.     public void setSex(String sex) {  
  40.         this.sex = sex;  
  41.     }  
  42. }  

4、创建测试类TestExportExcelUtil

这个类,主要是用来测试我们的工具类。具体代码如下:

[java]  view plain  copy
  1. package com.lyz.test;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import com.lyz.utils.excel.poi.ExportExcelUtil;  
  8. import com.lyz.utils.excel.poi.Student;  
  9.   
  10. /** 
  11.  * 测试文件导出 
  12.  * @author liuyazhuang 
  13.  * 
  14.  */  
  15. public class TestExportExcelUtil {  
  16.       
  17.     public static void main(String[] args) throws Exception{  
  18.         ExportExcelUtil<Student> util = new ExportExcelUtil<Student>();  
  19.          // 准备数据  
  20.         List<Student> list = new ArrayList<>();  
  21.         for (int i = 0; i < 10; i++) {  
  22.              list.add(new Student(111,"张三asdf","男"));  
  23.              list.add(new Student(111,"李四asd","男"));  
  24.              list.add(new Student(111,"王五","女"));  
  25.         }  
  26.         String[] columnNames = { "ID""姓名""性别" };  
            String[] columns = {"id", "name", "sex"};
  27.         util.exportExcel("用户导出", columnNames,columns,list, new FileOutputStream("E:/test.xls"), ExportExcelUtil.EXCEL_FILE_2003);  
  28.     }  
  29. }  

5、测试

我们运行TestExportExcelUtil类,会发现在我们的E盘下生成了test.xls文件,具体如下:


三、项目扩展

以上实现均是在本地磁盘生成excel文件,但更多的时候,我们需要通过点击网页上的某个按钮来自动生成并下载Excel文档,那么,这又如何实现呢?下面我们就一起来实现这个功能。

1、扩展ExportExcelUtil类

根据Java的继承思想,我们不在ExportExcelUtil类上修改添加,我们创建一个ExportExcelUtil类的子类ExportExcelWrapper,这个类继承ExportExcelUtil的所有功能,同时,扩展了网页生成Excel的功能。具体代码如下:

[java]  view plain  copy
  1. package com.lyz.utils.excel.poi;  
  2.   
  3. import java.net.URLEncoder;  
  4. import java.util.Collection;  
  5.   
  6. import javax.servlet.http.HttpServletResponse;  
  7.   
  8. import org.apache.commons.lang3.StringUtils;  
  9.   
  10. /** 
  11.  * 包装类 
  12.  * @author liuyazhuang 
  13.  * 
  14.  * @param <T> 
  15.  */  
  16. public class ExportExcelWrapper<T> extends ExportExcelUtil<T> {  
  17.     /** 
  18.      * <p> 
  19.      * 导出带有头部标题行的Excel <br> 
  20.      * 时间格式默认:yyyy-MM-dd hh:mm:ss <br> 
  21.      * </p> 
  22.      *  
  23.      * @param title 表格标题 
  24.      * @param headers 头部标题集合 
  25.      * @param dataset 数据集合 
  26.      * @param out 输出流 
  27.      * @param version 2003 或者 2007,不传时默认生成2003版本 
  28.      */  
  29.     public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response,String version) {  
  30.         try {  
  31.             response.setContentType("application/vnd.ms-excel");    
  32.             response.addHeader("Content-Disposition""attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls");  
  33.             if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){  
  34.                 exportExcel2003(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd hh:mm:ss");  
  35.             }else{  
  36.                 exportExcel2007(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd hh:mm:ss");  
  37.             }  
  38.         } catch (Exception e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42. }  

这样,我们可以在Controller层调用ExportExcelWrapper将相关的数据和HttpServletResponse传递进来,即可实现通过网页生生并下载Excel文档了。

2、编写Controller类

[java]  view plain  copy
  1. @Controller("test")  
  2. @RequestMapping("/test")  
  3. public class TestController {  
  4.     @RequestMapping("/get/excel")  
  5.     public void getExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {  
  6.         // 准备数据  
  7.         List<Student> list = new ArrayList<>();  
  8.         for (int i = 0; i < 10; i++) {  
  9.              list.add(new Student(111,"张三asdf","男"));  
  10.              list.add(new Student(111,"李四asd","男"));  
  11.              list.add(new Student(111,"王五","女"));  
  12.         }  
  13.         String[] columnNames = { "ID""姓名"" 性别"};  
            String[] columns = {"id", "name", "sex"};
  14.         String fileName = "excel1";  
  15.         ExportExcelWrapper<Student> util = new ExportExcelWrapper<Student>();  
  16.         util.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);  
  17.     }  
  18. }  

猜你喜欢

转载自blog.csdn.net/qq_39291929/article/details/80665810