POI小demo
阅读原文时间:2023年07月09日阅读:2

使用poi需要先下载相关jar包(http://download.csdn.net/detail/wangkunisok/9454545)

poi-3.14-20160307.jar

poi-ooxml-3.14-20160307.jar

poi-ooxml-schemas-3.14-20160307.jar

xmlbeans-2.6.0.jar

PoiUtil.java

package com.zto.branchaging.web.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

/**
*
*
* @author leno
* @version v1.0
* @param
* 应用泛型,代表任意一个符合javabean风格的类
* 注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
* byte[]表jpg格式的图片数据
*/
public class PoiUtil {

 public void exportExcel(Collection<T> dataset, OutputStream out) {  
     exportExcel("POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd");  
 }

 public void exportExcel(String\[\] headers, Collection<T> dataset,  
         OutputStream out) {  
     exportExcel("POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd");  
 }

 public void exportExcel(String\[\] headers, Collection<T> dataset,  
         OutputStream out, String pattern) {  
     exportExcel("POI导出EXCEL文档", headers, dataset, out, pattern);  
 }

 /\*\*  
  \* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上  
  \*  
  \* @param title  
  \*            表格标题名  
  \* @param headers  
  \*            表格属性列名数组  
  \* @param dataset  
  \*            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的  
  \*            javabean属性的数据类型有基本数据类型及String,Date,byte\[\](图片数据)  
  \* @param out  
  \*            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中  
  \* @param pattern  
  \*            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"  
  \*/  
 @SuppressWarnings("unchecked")  
 public void exportExcel(String title, String\[\] headers,  
         Collection<T> dataset, OutputStream out, String pattern) {

     List result = new ArrayList();  
     List paramterList = Arrays.asList(dataset.toArray());  
     // 声明一个工作薄  
     HSSFWorkbook workbook = new HSSFWorkbook();

     //设定每个sheet存储的数据量为五万,不能超过六万五  
     int pageCount = (int)Math.ceil(dataset.size()/50000)+1;//需要创建的sheet个数  
     if(dataset.size()<=50000){  
         result = paramterList.subList(0, dataset.size());  
     }

     // 生成一个样式  
     HSSFCellStyle style = workbook.createCellStyle();  
     style.setAlignment(HSSFCellStyle.ALIGN\_CENTER); // 居中  

     for(int j=0;j<pageCount;j++){  
         int startIndex = j\*50000;  
         int endIndex = startIndex+50000;  
         if(pageCount-j==1){  
             endIndex = dataset.size();  
         }  
         result = paramterList.subList(startIndex, endIndex);  
         // 生成一个表格  
         HSSFSheet sheet = workbook.createSheet(title+"-"+String.valueOf(j+1));  
         // 设置表格默认列宽度为15个字节  
         sheet.setDefaultColumnWidth((short) 15);  
         sheet.setColumnWidth(1, 24\*256);  //设置列宽,第二列24个字符宽  
         // 产生表格标题行  
         HSSFRow row = sheet.createRow(0);  
         for (short i = 0; i < headers.length; i++) {  
             HSSFCell cell = row.createCell(i);  
             cell.setCellStyle(style);  
             HSSFRichTextString text = new HSSFRichTextString(headers\[i\]);  
             cell.setCellValue(text);  
         }  
         // 遍历集合数据,产生数据行  
         Iterator<T> it = result.iterator();  
         int index = 0;  
         while (it.hasNext()) {  
             index++;  
             row = sheet.createRow(index);  
             T t = (T) it.next();  
             // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值  
             Field\[\] fields = t.getClass().getDeclaredFields();  
             for (short i = 0; i < fields.length; i++) {  
                 HSSFCell cell = row.createCell(i);  
                 cell.setCellStyle(style);  
                 Field field = fields\[i\];  
                 String fieldName = field.getName();  
                 String getMethodName = "get"  
                         + fieldName.substring(0, 1).toUpperCase()  
                         + fieldName.substring(1);  
                 try {  
                     Class tCls = t.getClass();  
                     Method getMethod = tCls.getMethod(getMethodName,  
                             new Class\[\] {});  
                     Object value = getMethod.invoke(t, new Object\[\] {});

                      // 数据类型都当作字符串简单处理  
                     String textValue = String.valueOf(null==value?"":value);

                     if (textValue != null) {  
                         cell.setCellValue(textValue);  
                     }  
                 } catch (SecurityException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 } catch (NoSuchMethodException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 } catch (IllegalArgumentException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 } catch (IllegalAccessException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 } catch (InvocationTargetException e) {  
                     // TODO Auto-generated catch block  
                     e.printStackTrace();  
                 } finally {  
                     // 清理资源  
                 }  
             }

         }

     }  
     try {  
         workbook.write(out);  
     } catch (IOException e) {  
         // TODO Auto-generated catch block  
         e.printStackTrace();  
     }

 }

}

POIController.java

package com.branchaging.web.controller;
@Controller
@RequestMapping("/singleAmount")
public class POIController{

@Autowired  
private IQuantityStatisBiz quantityStatisBiz;

@RequestMapping("/doExclExport")  
@ResponseBody  
public String doExclExportt(NewLine line,HttpServletRequest req,HttpServletResponse res) {

    String realFilename = "..."+fileNameTime+".xls";  
    res.setContentType("application/vnd.ms-excel; charset=utf-8");  
    try {  
        res.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(realFilename,"UTF-8"));  
    } catch (UnsupportedEncodingException e1) {  
        // TODO Auto-generated catch block  
        e1.printStackTrace();  
    }  
    res.setCharacterEncoding("utf-8");

    PoiUtil<TimeLineAmountExport> ex = new PoiUtil<TimeLineAmountExport>();  
    String\[\] headers = { "排名", "线路名称", "运输类型", "","",""... };

    try {  
        OutputStream out=res.getOutputStream();  
        //OutputStream out = new FileOutputStream("E://singleAmount.xls");  
        ex.exportExcel(headers, listResult, out);  
        out.flush();  
        out.close();  
        System.out.println("excel导出成功!");  
    } catch (FileNotFoundException e) {  
        e.printStackTrace();  
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
    return null;  
}  

}

前台访问:(这种方式是在当前窗口下弹出下载提示,其他两种注释的方式,效果不好)

function doExclExport() {
var result = doCheck();
if("back"==result){
return;
}
if($("#endTime").val()==getEndDate()){
return;
}

location.href="/singleAmount/doExclExport?" + 'time=' + $("#endTime").val() + '&type='  
    + $("#mySelect").val() + "&ationType=" + $("#typeAtion").val()  
    + "&startSite=" + $("#startSite").val() + "&endSite="  
    + $("#endSite").val();  

// window.open("/singleAmount/doExclExport?" + 'time=' + $("#endTime").val() + '&type='
// + $("#mySelect").val() + "&ationType=" + $("#typeAtion").val()
// + "&startSite=" + $("#startSite").val() + "&endSite="
// + $("#endSite").val());

// var form=$("

");
// form.append('');
// form.append('');
// form.append('');
// form.append('');
// form.append('');
// form.submit();
}