Java導出excel並下載功能


我們使用的導出並下載功能是利用一個插件叫POI的插件提供的導出功能,很實用;首先先導入Jar包:

Jar包下載地址:http://poi.apache.org/   官方文檔地址:http://poi.apache.org/spreadsheet/quick-guide.html

Action代碼:

public  void exportToExcel(List<PortalContactVO> data) throws Exception  
    {  
        this.setEnableAccessRequest(true);
        this.setEnableAccessResponse(true);
        HttpServletRequest request = this.getRequest();
        HttpServletResponse response = this.getResponse();
        String randomNumber = request.getParameter("randomNumber");// session名稱
        try {
            session = request.getSession();
            session.setAttribute(randomNumber, new Double(1));
            // 導出的EXCEL文件名
            String exportFileName = "addressBook.xlsx";
            response.reset();
            response.setContentType("octets/stream");
            // response.setHeader("Content-Disposition","attachment;filename="+exportFileName);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + new String(exportFileName.getBytes("UTF-8"), "iso8859-1") + "\"");

            // 導出的EXCEL列屬性
            List<String> columnListName = new ArrayList<String>();
            columnListName.add("userName&姓名");
            columnListName.add("mobile&手機");
            columnListName.add("shopTel&分店電話");
            columnListName.add("postName&職位");
            columnListName.add("email&郵箱");
            columnListName.add("shopAddress&分店地址");
            Bean2ExcelConversionUtils.beans2excelFile07(columnListName, data, response.getOutputStream());
            session.setAttribute(randomNumber, new Double(100));

        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute(randomNumber, new Double(100));
        } catch (Throwable e) {
            e.printStackTrace();
            session.setAttribute(randomNumber, new Double(100));
        }
    }

JSP代碼:

   <form id="exportForm">    
       <input class="btnStyle" type="submit" id="inputExport" value="導出" onclick="exportToExcel()" />
   </form>
function exportToExcel() {
            var randomNumber=new Date().getTime();
            top.$.jBox.tip("正在導出...", 'loading');
            var exportDate = "${ctx}/xxxAction.do?method=export&randomNumber="+randomNumber;
            $("#exportForm").attr("action", exportDate);
            $("#exportForm").attr("method","post");
            $("#exportForm").submit();
        }

 

因為是使用的插件,所以需要引入一個工具類(下面的工具類直接復制到新建的類文件里面即可)

也可以通過:http://download.csdn.net/detail/work201003/9404952 進行下載

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

/**
 * @author Tan Jiangyong
 * @date 2013-9-3 下午3:36:43
 * @version V1.0
 */
@SuppressWarnings("all")
public class Bean2ExcelConversionUtils {
    private static final String PATTERN="yyyy-MM-dd HH:mm:ss";    //excel日期格式,默認配置
    private static final String DATE_PATTERN="yyyy-MM-dd";        //excel日期格式
    private static final String DATE_HH_PATTERN="HH:mm:ss";        //excel時間格式
    private static final int TOTAL_SIZE=40000;                    //每個excel寫入多少數據(默認配置)
    private static final int MAX_SHEET_SIZE=10000;                //每一個sheet的大小(默認配置)
    private static final int COLUMN_WIDTH_WORD=25;                //列寬,默認漢字個數為25個
    private static final int FLUSH_ROWS=100;                    //每生成excel行數,內存中緩存記錄數清空(目的,避免零時文件過大)
    
    /**
     * 07、10辦公版EXCEL導出(數據直接寫到服務器的EXCEL里,以下載的形式,下載導出的數據)
     * @param listName        列表頭名稱
     * @param beans         實體集合
     * @param result        數字字典Map集
     * @param filePath        服務器存放文件路徑
     * @param fileName         文件名稱
     * @param totalSize     EXCEL條數量
     * @param maxSheetSize     sheet頁條數量
     * @return              文件集合
     * @throws Exception    
     */
    public static <T> List<File> beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
        if(totalSize==null || totalSize<=0)
            totalSize=TOTAL_SIZE;
        if(maxSheetSize==null || maxSheetSize<=0)
            maxSheetSize=MAX_SHEET_SIZE;
        if(fileName==null)
            fileName="";
        return beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
    }
    /**
     * 07、10辦公版EXCEL導出(數據直接寫到服務器的EXCEL里,以下載的形式,下載導出的數據)
     * @param listName        列表頭名稱
     * @param beans         實體集合
     * @param result        數字字典Map集
     * @param filePath        服務器存放文件路徑
     * @param fileName         文件名稱
     * @param totalSize     EXCEL條數量
     * @param maxSheetSize     sheet頁條數量
     * @param request        客戶端請求對象
     * @param response        客戶端響應對象
     * @throws Exception
     */
    public static <T> void beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{
        if(totalSize==null || totalSize<=0)
            totalSize=TOTAL_SIZE;
        if(maxSheetSize==null || maxSheetSize<=0)
            maxSheetSize=MAX_SHEET_SIZE;
        if(fileName==null)
            fileName="";
        List<File> files = beans2excelFile2007(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
        DownLoadUtils.downLoadFiles(files, filePath, request, response);
    }
    
    /**
     * 07、10辦公版EXCEL導出,每個EXCEL組織數據
     * @param listName         列表頭名稱
     * @param beans             實體集合
     * @param result         數字字典Map集
     * @param filePath         服務器存放文件路徑
     * @param fileName         文件名稱
     * @param totalSize      EXCEL條數量
     * @param maxSheetSize  sheet頁條數量
     * @return                文件集合
     * @throws Exception
     */
    private static <T> List<File> beans2excelFile2007(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        List<File> listFile=new ArrayList<File>();//返回的文件集合
        
        int size=beans==null?0:beans.size();
        String fileSuffixName=".xlsx";//后綴
        String path="";//文件路徑
        Integer startIdx=0;//數據讀取的起始行
        Integer endIdx=0;//數據讀取的結束行
        (new File(filePath)).mkdirs(); //沒有該目錄創建目錄
        if(size==0){
            startIdx=0;
            endIdx=(totalSize)>size?size:(totalSize);
            String name=fileName+"_第0-0條數據";
            path=filePath+File.separatorChar+name+fileSuffixName;
            Workbook wb =new SXSSFWorkbook();
            buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
            //沒有文件,創建文件
            File file = new File(path);
            if (!file.exists()){  
                file.createNewFile();  
            }
            FileOutputStream out=new FileOutputStream(file);
            wb.write(out);
            out.close();
            return listFile;
        }
        for (int i = 0; i < size;i++) {
            int remainder=i%totalSize;
            if(size==0 || remainder==0){
                startIdx=i;
                endIdx=(i+totalSize)>size?size:(i+totalSize);
                String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"條數據";
                path=filePath+"/"+name+fileSuffixName;
                Workbook wb =new SXSSFWorkbook();
                buildExcelDocument2007(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
                //沒有文件,創建文件
                File file = new File(path);
                if (!file.exists()){  
                    file.createNewFile();  
                }
                FileOutputStream out=new FileOutputStream(file);
                wb.write(out);
                out.close();
                listFile.add(file);
            }else if((size-i)<totalSize && i>endIdx){//最后,不滿一萬條
                startIdx=i;
                endIdx=i+totalSize;
                String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"條數據";
                path=filePath+name+"."+fileSuffixName;//沒有文件,創建文件
                Workbook wb =new SXSSFWorkbook();
                buildExcelDocument2007(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);
                //沒有文件,創建文件
                File file = new File(path);
                if (!file.exists()){  
                    file.createNewFile();  
                }
                FileOutputStream out=new FileOutputStream(file);
                wb.write(out);
                out.close();
                listFile.add(file);
            }
        }
        return listFile;
    }
    
    /**
     * 07、10辦公版EXCEL導出,每個EXCEL寫入數據
     * @param wb            EXCEL工作薄
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param result        數字字典Map集
     * @param startIdx        數據集合,開始行
     * @param endIdx        數據集合,結束始行
     * @param maxSheetSize    SHEET頁條數
     * @throws Exception 
     */
    private static <T> void buildExcelDocument2007(Workbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception
    {
        int totalSize=endIdx-startIdx;//總共條數
        try
        {
            CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
            List titles = new ArrayList();
            List beanAttrNames = new ArrayList();
            boolean flagListExists=false;
            List flagList=new ArrayList();
            List widthList=new ArrayList();
            HashMap<String,String> dateMap=new HashMap<String, String>();
            String[] header = new String[listName.size()];
            int rows_max = 0;//標題占多少列
            for (int i=0;i<listName.size();i++)
            {
                String[] str=listName.get(i).split("&");
                String en_name=str[0];
                String zh_name=str[1];
                beanAttrNames.add(i,en_name);
                titles.add(i, zh_name);
                header[i]=zh_name;
                if (zh_name.split("_").length > rows_max) {
                    rows_max = zh_name.split("_").length;
                }
                if(str.length>2){
                    String flag=str[2];
                    flagList.add(i,flag);
                    if(!flagListExists)
                        flagListExists=true;
                }
                if(str.length>3){
                    widthList.add(str[3]);
                }
                if(str.length>4){
                    dateMap.put(en_name, str[4]);
                }
            }

            PropertyDescriptor[] props = null;

            int size=endIdx-startIdx;
            Sheet sheet=null;
            
            //如果沒有數據,導出表頭
            if(size==0){
                sheet=ExcelHeadUtils.getExcelHead2007(wb, header, "Sheet1");
                sheet.setDefaultRowHeight((short)350);//高度
                setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                return ;
            }
            int u=1;//用來創建每個sheet的行
            int h=0;//用來標注每個sheet也得名字:多少行-多少行
            for (int i = startIdx; i < endIdx ; i++) {
                int remainder=h%maxSheetSize;
                if(size==0 || i==startIdx || remainder==0){
                    u=1;
                    int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);
                    sheet=ExcelHeadUtils.getExcelHead2007(wb, header,"第"+(h+1)+"-"+section+"條");
                    sheet.createFreezePane( 1, rows_max, 1, rows_max);
                    sheet.setDefaultRowHeight((short)350);//高度
                    setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                }
                if(props==null)
                    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
                Object bean = beans.get(i);
                Row row = sheet.createRow(u+rows_max-1);
                u++;
                h++;
                for (int j = 0; j < beanAttrNames.size(); j++) {
                    String beanAttrName = (String)beanAttrNames.get(j);
                    String flag="";
                    if(flagListExists)
                        flag=(String)flagList.get(j);
                    for (int k = 0; k < props.length; k++) {
                        String propName = props[k].getName();
                        if (propName.equals(beanAttrName))
                        {
                            String pattern=dateMap.get(beanAttrName);
                            Cell cell = row.createCell((short)j);

                            Object cellValue = callGetter(bean, props[k],pattern);
                            if("true".equalsIgnoreCase(flag)){
                                if(result!=null){
                                    HashMap<String,String> hash=result.get(beanAttrName);
                                    if(hash!=null)
                                        cellValue=hash.get(cellValue);
                                }
                            }
                            if (cellValue == null) {
                                cellValue = "";
                            }
                            setExcelCellText2007(cell, cellValue.toString(),cellStyle);
                        }
                    }
                }
                 //每當行數達到設置的值就刷新數據到硬盤,以清理內存
                if(i%FLUSH_ROWS==0){
                   ((SXSSFSheet)sheet).flushRows();
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 07、10辦公版EXCEL導出(直接以流的方式,寫到客戶端,導出的EXCEL文件只有一個)
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    SHEET頁的條數
     * @param outputStream    客戶端輸出流
     * @throws Exception
     */
    public static <T> void beans2excelFile07(List<String> listName,List<T> beans, OutputStream outputStream) throws Exception{
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        if (outputStream == null) {
            throw new Exception("outputStream is null when create excel document");
        }
        Workbook wb =new SXSSFWorkbook();
        beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, outputStream);
        try {
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new Exception(e);
        } 
    }
    /**
     * 07、10辦公版EXCEL導出(直接以流的方式,寫到客戶端,導出的EXCEL文件只有一個)
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    SHEET頁的條數
     * @param outputStream    客戶端輸出流
     * @throws Exception
     */
    public static <T> void beans2excelFile07(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        if (outputStream == null) {
            throw new Exception("outputStream is null when create excel document");
        }
        if(maxSheetSize==null || maxSheetSize<=0){
            maxSheetSize=MAX_SHEET_SIZE;
        }
        if(sheetName==null || "".equals(sheetName.trim())){
            sheetName="Sheet";
        }
        Workbook wb =new SXSSFWorkbook();
        if(maxSheetSize==null || maxSheetSize<=0){
            maxSheetSize=MAX_SHEET_SIZE;
        }
        buildExcelDocument2007(wb, listName, beans,result,sheetName,maxSheetSize);
        try {
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new Exception(e);
        } 
    }
    /**
     * 
     * @param listName
     * @param beans
     * @param response
     * @param fileName 導出的文件名稱
     * @throws Exception
     */
    public static <T> void beans2excelFile07(List<String> listName, List<T> beans, HttpServletResponse response,String fileName) throws Exception {
        response.reset();
        response.setContentType("octets/stream");
        response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(fileName, "UTF-8"));
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        if (response.getOutputStream() == null) {
            throw new Exception("outputStream is null when create excel document");
        }
        beans2excelFile07(listName, beans, null, null, MAX_SHEET_SIZE, response.getOutputStream());
    }
    /**
     * 07、10辦公版EXCEL導出,EXCEL寫入數據
     * @param wb            EXCEL工作薄
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    SHEET頁的條數
     * @throws Exception 
     */
    private static <T> void buildExcelDocument2007(Workbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize) throws Exception
    {
        try
        {
            CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
            List titles = new ArrayList();
            List beanAttrNames = new ArrayList();
            List widthList = new ArrayList();
            HashMap<String,String> dateMap=new HashMap<String, String>();
            String[] header = new String[listName.size()];
            int rows_max = 0;//標題占多少列
            List flagList=new ArrayList();
            boolean flagListExists=false;
            for (int i=0;i<listName.size();i++)
            {
                String[] str=listName.get(i).split("&");
                String en_name=str[0];
                String zh_name=str[1];
                beanAttrNames.add(i,en_name);
                titles.add(i, zh_name);
                header[i]=zh_name;
                if (zh_name.split("_").length > rows_max) {
                    rows_max = zh_name.split("_").length;
                }
                if(str.length>2){
                    String flag=str[2];
                    flagList.add(i,flag);
                    if(!flagListExists)
                        flagListExists=true;
                }
                if(str.length>3){
                    widthList.add(str[3]);
                }
                if(str.length>4){
                    dateMap.put(en_name, str[4]);
                }
            }

            PropertyDescriptor[] props = null;

            int size=beans==null?0:beans.size();
            Sheet sheet=null;
            
            //如果沒有數據,導出表頭
            if(size==0){
                sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);
                sheet.setDefaultRowHeight((short)350);//高度
                setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                return ;
            }
            
            for (int i = 0; i < size ; i++) {
                int remainder=i%maxSheetSize;
                if(size==0 || i==0 || remainder==0){
                    sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName+(i/maxSheetSize));
                    sheet.createFreezePane( 1, rows_max, 1, rows_max);
                    sheet.setDefaultRowHeight((short)350);//高度
                    setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                }
                if(props==null)
                    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
                Object bean = beans.get(i);
                Row row = sheet.createRow(remainder+rows_max);
                for (int j = 0; j < beanAttrNames.size(); j++) {
                    String beanAttrName = (String)beanAttrNames.get(j);
                    String flag="";
                    if(flagListExists)
                        flag=(String)flagList.get(j);
                    for (int k = 0; k < props.length; k++) {
                        String propName = props[k].getName();
                        if (propName.equals(beanAttrName))
                        {
                            String pattern=dateMap.get(beanAttrName);
                            Cell cell = row.createCell((short)j);

                            Object cellValue = callGetter(bean, props[k],pattern);
                            if("true".equalsIgnoreCase(flag)){
                                if(result!=null){
                                    HashMap<String,String> hash=result.get(beanAttrName);
                                    if(hash!=null)
                                        cellValue=hash.get(cellValue);
                                }
                            }
                            if (cellValue == null) {
                                cellValue = "";
                            }
                            setExcelCellText2007(cell, cellValue.toString(),cellStyle);
                        }
                    }
                }
                 //每當行數達到設置的值就刷新數據到硬盤,以清理內存
                if(i%FLUSH_ROWS==0){
                   ((SXSSFSheet)sheet).flushRows();
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * 07、10辦公版EXCEL導出(直接以流的方式,寫到客戶端,導出的EXCEL文件只有一個)
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    SHEET頁的條數
     * @param outputStream    客戶端輸出流
     * @throws Exception
     */
    public static <T> void beans2excelFile07List(List<ArrayList<String>> listColumnName,List<List> list2beans,HashMap<String,HashMap<String,HashMap<String,String>>> result,List<String> listSheetName, OutputStream outputStream) throws Exception{
        if ((listColumnName == null) || (listColumnName.size() == 0)) {
            throw new Exception("listColumnName is null when create excel document");
        }
        if (list2beans.size() != listColumnName.size()) {
            throw new Exception("list2beans and listColumnName size Unequal");
        }
        if (outputStream == null) {
            throw new Exception("outputStream is null when create excel document");
        }
        Workbook wb =new SXSSFWorkbook();
        buildExcelDocument2007List(wb, listColumnName, list2beans, result, listSheetName);
        try {
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new Exception(e);
        } 
    }
    /**
     * 07、10辦公版EXCEL導出,EXCEL寫入數據
     * @param wb            EXCEL工作薄
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    SHEET頁的條數
     * @throws Exception 
     */
    private static <T> void buildExcelDocument2007List(Workbook wb, List<ArrayList<String>> listColumnName,List<List> list2beans,HashMap<String,HashMap<String,HashMap<String,String>>> resultMap,List<String> listSheetName) throws Exception
    {
        try
        {
            int sheets=listColumnName.size();
            boolean sheetNameIsNullFlag=false;
            if(listSheetName==null || listSheetName.size()!=sheets){
                sheetNameIsNullFlag=true;
            }
            for (int s = 0; s < sheets; s++) {
                String sheetName="Sheet"+s;
                if(!sheetNameIsNullFlag){
                    sheetName=listSheetName.get(s);
                }
                List<String> listName=listColumnName.get(s);
                CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
                List titles = new ArrayList();
                List beanAttrNames = new ArrayList();
                List widthList = new ArrayList();
                HashMap<String,String> dateMap=new HashMap<String, String>();
                String[] header = new String[listName.size()];
                int rows_max = 0;//標題占多少列
                List flagList=new ArrayList();
                boolean flagListExists=false;
                for (int i=0;i<listName.size();i++)
                {
                    String[] str=listName.get(i).split("&");
                    String en_name=str[0];
                    String zh_name=str[1];
                    beanAttrNames.add(i,en_name);
                    titles.add(i, zh_name);
                    header[i]=zh_name;
                    if (zh_name.split("_").length > rows_max) {
                        rows_max = zh_name.split("_").length;
                    }
                    if(str.length>2){
                        String flag=str[2];
                        flagList.add(i,flag);
                        if(!flagListExists)
                            flagListExists=true;
                    }
                    if(str.length>3){
                        widthList.add(str[3]);
                    }
                    if(str.length>4){
                        dateMap.put(en_name, str[4]);
                    }
                }
    
                PropertyDescriptor[] props = null;
                ArrayList<T> beans=(ArrayList<T>)list2beans.get(s);
                int size=beans==null?0:beans.size();
                Sheet sheet=null;
                
                //如果沒有數據,導出表頭
                if(size==0){
                    sheet=ExcelHeadUtils.getExcelHead2007(wb, header, sheetName);
                    sheet.setDefaultRowHeight((short)350);//高度
                    setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                    return ;
                }
                
                HashMap<String,HashMap<String,String>> result=null;
                if(resultMap!=null){
                    result=resultMap.get(sheetName);
                }
                sheet=ExcelHeadUtils.getExcelHead2007(wb, header,sheetName);
                sheet.createFreezePane( 1, rows_max, 1, rows_max);
                sheet.setDefaultRowHeight((short)350);//高度
                setColumnWidth2007(widthList, sheet,beanAttrNames.size());
                for (int i = 0; i < size ; i++) {
                    if(props==null)
                        props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
                    Object bean = beans.get(i);
                    Row row = sheet.createRow(rows_max+i);
                    for (int j = 0; j < beanAttrNames.size(); j++) {
                        String beanAttrName = (String)beanAttrNames.get(j);
                        String flag="";
                        if(flagListExists)
                            flag=(String)flagList.get(j);
                        for (int k = 0; k < props.length; k++) {
                            String propName = props[k].getName();
                            if (propName.equals(beanAttrName))
                            {
                                String pattern=dateMap.get(beanAttrName);
                                Cell cell = row.createCell((short)j);
    
                                Object cellValue = callGetter(bean, props[k],pattern);
                                if("true".equalsIgnoreCase(flag)){
                                    if(result!=null){
                                        HashMap<String,String> hash=result.get(beanAttrName);
                                        if(hash!=null)
                                            cellValue=hash.get(cellValue);
                                    }
                                }
                                if (cellValue == null) {
                                    cellValue = "";
                                }
                                setExcelCellText2007(cell, cellValue.toString(),cellStyle);
                            }
                        }
                    }
                     //每當行數達到設置的值就刷新數據到硬盤,以清理內存
                    if(i%FLUSH_ROWS==0){
                       ((SXSSFSheet)sheet).flushRows();
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    /**
     * 07、10辦公版EXCEL導出,單元格設置
     * @param cell        單元格對象
     * @param text        單元格文本內容
     * @param cellStyle    單元格格式
     */
    private static void setExcelCellText2007(Cell cell, Object text,CellStyle cellStyle)
    {
        cell.setCellValue(text.toString());
        cell.setCellType(1);//單元格類型
        cell.setCellStyle(cellStyle);
    }
    
    /**
     * 07、10辦公版EXCEL導出,單元格寬度設置
     * @param widthList        列寬集合
     * @param sheet            sheet對象
     * @param allSize        總列數
     */
    private static void setColumnWidth2007(List widthList,Sheet sheet,int allSize){
        if(widthList!=null && widthList.size()>0){
            int size=widthList.size();
            for (int i = 0; i < size; i++) {
                try {
                    Integer width=Integer.parseInt((String) widthList.get(i));
                    sheet.setColumnWidth((short) i,width*256);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
        }else{
            for (int i = 0; i < allSize; i++) {
                try {
                    sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
        
        }
    }
    
    /**
     * 03、WPS:EXCEL導出(數據直接寫到服務器的EXCEL里,以下載的形式,下載導出的數據)
     * @param listName            列表頭名稱
     * @param beans                實體集合
     * @param result            數字字典Map集
     * @param filePath            服務器存放文件路徑
     * @param fileName            文件名稱
     * @param totalSize            EXCEL條數量
     * @param maxSheetSize        sheet頁條數量
     * @return List<File>        文件集合
     * @throws Exception
     */
    public static <T> List<File> beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
        if(totalSize==null || totalSize<=0)
            totalSize=TOTAL_SIZE;
        if(maxSheetSize==null || maxSheetSize<=0)
            maxSheetSize=MAX_SHEET_SIZE;
        if(fileName==null)
            fileName="";
        return beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
    }
    /**
     * 03、WPS:EXCEL導出(數據直接寫到服務器的EXCEL里,以下載的形式,下載導出的數據)
     * @param listName            列表頭名稱
     * @param beans                實體集合
     * @param result            數字字典Map集
     * @param filePath            服務器存放文件路徑
     * @param fileName            文件名稱
     * @param totalSize            EXCEL條數量
     * @param maxSheetSize        sheet頁條數量
     * @param request        客戶端請求對象
     * @param response        客戶端響應對象
     * @throws Exception
     */
    public static <T> void beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize,HttpServletRequest request,HttpServletResponse response) throws Exception{
        if(totalSize==null || totalSize<=0)
            totalSize=TOTAL_SIZE;
        if(maxSheetSize==null || maxSheetSize<=0)
            maxSheetSize=MAX_SHEET_SIZE;
        if(fileName==null)
            fileName="";
        List<File> files=beans2excelFile2003(listName, beans, result, filePath, fileName,totalSize,maxSheetSize);
        DownLoadUtils.downLoadFiles(files, filePath, request, response);
    }
    /**
     *  03、WPS:EXCEL導出,每個EXCEL組織數據
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param result        數字字典Map集
     * @param filePath        服務器存放文件路徑
     * @param fileName        文件名稱
     * @param totalSize        EXCEL條數量
     * @param maxSheetSize    sheet頁條數量
     * @return                文件集合
     * @throws Exception
     */
    private static <T> List<File> beans2excelFile2003(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String filePath,String fileName,Integer totalSize,Integer maxSheetSize) throws Exception{
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        List<File> listFile=new ArrayList<File>();//返回的文件集合
        
        int size=beans==null?0:beans.size();
        String fileSuffixName=".xls";//后綴
        String path="";//文件路徑
        Integer startIdx=0;//數據讀取的起始行
        Integer endIdx=0;//數據讀取的結束行
        (new File(filePath)).mkdirs(); //沒有該目錄創建目錄
        if(size==0){
            startIdx=0;
            endIdx=(totalSize)>size?size:(totalSize);
            String name=fileName+"_第0-0條數據";
            path=filePath+File.separatorChar+name+fileSuffixName;
            HSSFWorkbook wb =new HSSFWorkbook();
            buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
            //沒有文件,創建文件
            File file = new File(path);
            if (!file.exists()){  
                file.createNewFile();  
            }
            FileOutputStream out=new FileOutputStream(file);
            wb.write(out);
            out.close();
            return listFile;
        }
        for (int i = 0; i < size;i++) {
            int remainder=i%totalSize;
            if(size==0 || remainder==0){
                startIdx=i;
                endIdx=(i+totalSize)>size?size:(i+totalSize);
                String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"條數據";
                path=filePath+"/"+name+fileSuffixName;
                HSSFWorkbook wb =new HSSFWorkbook();
                buildExcelDocument2003(wb, listName, beans,result,startIdx,endIdx,maxSheetSize);
                //沒有文件,創建文件
                File file = new File(path);
                if (!file.exists()){  
                    file.createNewFile();  
                }
                FileOutputStream out=new FileOutputStream(file);
                wb.write(out);
                out.close();
                listFile.add(file);
            }else if((size-i)<totalSize && i>endIdx){//最后,不滿一萬條
                startIdx=i;
                endIdx=i+totalSize;
                String name=fileName+"_第"+(startIdx+1)+"-"+(endIdx)+"條數據";
                path=filePath+name+"."+fileSuffixName;//沒有文件,創建文件
                HSSFWorkbook wb =new HSSFWorkbook();
                buildExcelDocument2003(wb, listName, beans, result,startIdx,endIdx,maxSheetSize);
                //沒有文件,創建文件
                File file = new File(path);
                if (!file.exists()){  
                    file.createNewFile();  
                }
                FileOutputStream out=new FileOutputStream(file);
                wb.write(out);
                out.close();
                listFile.add(file);
            }
        }
        return listFile;
    }
    
    /**
     * 03,WPS:EXCEL導出,每個EXCEL寫入數據
     * @param wb            EXCEL工作薄
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param result        數字字典Map集
     * @param startIdx        數據集合,開始行
     * @param endIdx        數據集合,結束始行
     * @param maxSheetSize    SHEET頁條數
     * @throws Exception 
     */
    private static <T> void buildExcelDocument2003(HSSFWorkbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,Integer startIdx,Integer endIdx,Integer maxSheetSize) throws Exception
    {
        int totalSize=endIdx-startIdx;//總共條數
        try
        {
            CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
            List titles = new ArrayList();
            List beanAttrNames = new ArrayList();
            List widthList=new ArrayList();
            String[] header = new String[listName.size()];
            List flagList=new ArrayList();
            boolean flagListExists=false;
            int rows_max = 0;//標題占多少列
            HashMap<String,String> dateMap=new HashMap<String, String>();
            for (int i=0;i<listName.size();i++)
            {
                String[] str=listName.get(i).split("&");
                String en_name=str[0];
                String zh_name=str[1];
                beanAttrNames.add(i,en_name);
                titles.add(i, zh_name);
                header[i]=zh_name;
                if (zh_name.split("_").length > rows_max) {
                    rows_max = zh_name.split("_").length;
                }
                if(str.length>2){
                    String flag=str[2];
                    flagList.add(i,flag);
                    if(!flagListExists)
                        flagListExists=true;
                }
                if(str.length>3){
                    widthList.add(str[3]);
                }
                if(str.length>4){
                    dateMap.put(en_name, str[4]);
                }
            }

            PropertyDescriptor[] props = null;

            int size=endIdx-startIdx;
            HSSFSheet sheet=null;
            
            //如果沒有數據,導出表頭
            if(size==0){
                sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "Sheet1");
                sheet.setDefaultRowHeight((short)350);//高度
                setColumnWidth2003(widthList, sheet,beanAttrNames.size());
                return ;
            }
            int u=1;//用來創建每個sheet的行
            int h=0;//用來標注每個sheet也得名字:多少行-多少行
            for (int i = startIdx; i < endIdx ; i++) {
                int remainder=h%maxSheetSize;
                if(size==0 || i==startIdx || remainder==0){
                    u=1;
                    int section=(h+maxSheetSize)>totalSize?totalSize:(h+maxSheetSize);
                    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, "第"+(h+1)+"-"+section+"條");
                    sheet.createFreezePane( 1, rows_max, 1, rows_max);
                    sheet.setDefaultRowHeight((short)350);//高度
                    setColumnWidth2003(widthList, sheet,beanAttrNames.size());
                }
                if(props==null)
                    props=Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
                Object bean = beans.get(i);
                HSSFRow row = sheet.createRow(u+rows_max-1);
                u++;
                h++;
                for (int j = 0; j < beanAttrNames.size(); j++) {
                    String beanAttrName = (String)beanAttrNames.get(j);
                    String flag=null;
                    if(flagListExists)
                        flag=(String)flagList.get(j);
                    for (int k = 0; k < props.length; k++) {
                        String propName = props[k].getName();
                        if (propName.equals(beanAttrName))
                        {
                            String pattern=dateMap.get(beanAttrName);
                            HSSFCell cell = row.createCell((short)j);
                            Object cellValue = callGetter(bean, props[k],pattern);
                            if("true".equalsIgnoreCase(flag)){
                                if(result!=null){
                                    HashMap<String,String> hash=result.get(beanAttrName);
                                    if(hash!=null)
                                        cellValue=hash.get(cellValue);
                                }
                            }
                            if (cellValue == null) {
                                cellValue = "";
                            }
                            setExcelCellText2003(cell, cellValue.toString(),cellStyle);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }
    
    /**
     * 03,WPS:EXCEL導出(直接以流的方式,寫到客戶端,導出的EXCEL文件只有一個)
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    sheet頁條數量
     * @param outputStream    客戶端輸出流
     * @throws Exception
     */
    public static <T> void beans2excelFile03(List<String> listName,List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize, OutputStream outputStream) throws Exception{
        if ((listName == null) || (listName.size() == 0)) {
            throw new Exception("listName is null when create excel document");
        }
        if(maxSheetSize==null || maxSheetSize<=0){
            maxSheetSize=MAX_SHEET_SIZE;
        }
        if(sheetName==null || "".equals(sheetName.trim())){
            sheetName="Sheet";
        }
        HSSFWorkbook wb =new HSSFWorkbook();
        if(maxSheetSize==null || maxSheetSize<=0)
            maxSheetSize=MAX_SHEET_SIZE;
        buildExcelDocument2003(wb, listName, beans,result,sheetName,maxSheetSize);
        try {
            wb.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            throw new Exception(e);
        } 
    }

    /**
     * 03,WPS:EXCEL導出,EXCEL寫入數據
     * @param wb            EXCEL工作薄
     * @param listName        列表頭名稱
     * @param beans            實體集合
     * @param maxSheetSize    sheet頁條數量
     * @throws Exception 
     */
    private static <T> void buildExcelDocument2003(HSSFWorkbook wb, List<String> listName, List<T> beans,HashMap<String,HashMap<String,String>> result,String sheetName,Integer maxSheetSize) throws Exception
    {
        try
        {
            CellStyle cellStyle=POIUtils.getCellStyleFont(wb,null);
            List titles = new ArrayList();
            List beanAttrNames = new ArrayList();
            List widthList = new ArrayList();
            HashMap<String,String> dateMap=new HashMap<String, String>();
            String[] header = new String[listName.size()];
            int rows_max = 0;//標題占多少列
            List flagList=new ArrayList();
            boolean flagListExists=false;
            for (int i=0;i<listName.size();i++)
            {
                String[] str=listName.get(i).split("&");
                String en_name=str[0];
                String zh_name=str[1];
                beanAttrNames.add(i,en_name);
                titles.add(i, zh_name);    
                header[i]=zh_name;
                if (zh_name.split("_").length > rows_max) {
                    rows_max = zh_name.split("_").length;
                }
                if(str.length>2){
                    String flag=str[2];
                    flagList.add(i,flag);
                    if(!flagListExists)
                        flagListExists=true;
                }
                if(str.length>3){
                    widthList.add(str[3]);
                }
                if(str.length>4){
                    dateMap.put(en_name, str[4]);
                }
            }
            PropertyDescriptor[] props =null;

            int size=beans==null?0:beans.size();
            HSSFSheet sheet=null;
            //如果沒有數據,導出表頭
            if(size==0){
                sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName);
                setColumnWidth2003(widthList, sheet,beanAttrNames.size());
                sheet.setDefaultRowHeight((short)350);//高度
                return ;
            }
            for (int i = 0; i < size ; i++) {
                int remainder=i%maxSheetSize;
                if(size==0 || i==0 || remainder==0){
                    sheet=ExcelHeadUtils.getExcelHead2003(wb, header, sheetName+(i/maxSheetSize));
                    sheet.createFreezePane( 1, rows_max, 1, rows_max);
                    setColumnWidth2003(widthList, sheet,beanAttrNames.size());
                    sheet.setDefaultRowHeight((short)350);//高度
                }
                if(props==null)
                    props= Introspector.getBeanInfo(beans.get(0).getClass()).getPropertyDescriptors();
                Object bean = beans.get(i);
                HSSFRow row = sheet.createRow(remainder+rows_max);
                for (int j = 0; j < beanAttrNames.size(); j++) {

                    String beanAttrName = (String)beanAttrNames.get(j);
                    String flag=null;
                    if(flagListExists)
                        flag=(String)flagList.get(j);
                    for (int k = 0; k < props.length; k++) {
                        String propName = props[k].getName();
                        if (propName.equals(beanAttrName))
                        {
                            String pattern=dateMap.get(beanAttrName);
                            HSSFCell cell = row.createCell((short)j);
                            Object cellValue = callGetter(bean, props[k],pattern);
                            if("true".equalsIgnoreCase(flag)){
                                if(result!=null){
                                    HashMap<String,String> hash=result.get(beanAttrName);
                                    if(hash!=null)
                                        cellValue=hash.get(cellValue);
                                }
                            }
                            if (cellValue == null) {
                                cellValue = "";
                            }
                            setExcelCellText2003(cell, cellValue.toString(),cellStyle);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /**
     * 03,WPS:EXCEL導出,單元格設置
     * @param cell        單元格對象
     * @param text        單元格文本內容
     * @param cellStyle    單元格格式
     */
    private static void setExcelCellText2003(HSSFCell cell, Object text,CellStyle cellStyle)
    {
        cell.setCellValue(text.toString());
        cell.setCellType(1);//單元格類型
        cell.setCellStyle(cellStyle);
    }

    /**
     * 03,WPS:EXCEL導出,單元格寬度設置
     * @param widthList        列寬集合
     * @param sheet            sheet對象
     * @param allSize        總列數
     */
    private static void setColumnWidth2003(List widthList,HSSFSheet sheet,int allSize){
        if(widthList!=null && widthList.size()>0){
            int size=widthList.size();
            for (int i = 0; i < size; i++) {
                try {
                    Integer width=Integer.parseInt((String) widthList.get(i));
                    sheet.setColumnWidth((short) i,width*256);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
        }else{
            for (int i = 0; i < allSize; i++) {
                try {
                    sheet.setColumnWidth((short) i,COLUMN_WIDTH_WORD*256);
                } catch (NumberFormatException e) {
                    continue;
                }
            }
        }
    }

    /**
     * 根據反射,獲取實體屬性的值
     * @param target    實體屬性
     * @param prop        反射調用類
     * @param pattern    日期格式
     * @return            
     */
    private static Object callGetter(Object target, PropertyDescriptor prop,String pattern) {
        Object o = null;
        if (prop.getReadMethod() != null) {
            try {
                o = prop.getReadMethod().invoke(target, null);
                if (Date.class.equals(prop.getPropertyType())) {
                    if(pattern!=null && !"".equals(pattern)){
                        try {
                            o = new SimpleDateFormat(pattern).format(o);
                        } catch (Exception e) {
                            o = new SimpleDateFormat(PATTERN).format(o);
                        }
                    }else{
                        o = formatDate(o);
                    }
                }
            } catch (Exception e) {
                o = null;
            }
        }
        return o;
    }
    
    /**
     * 日期轉換
     * @param date
     * @return 字符串的日期
     */
    private static String formatDate(Object date) {
        if(date==null)
            return "";
        String dateStr = new SimpleDateFormat(DATE_HH_PATTERN).format(date);
        if("00:00:00".equals(dateStr)){
            return new SimpleDateFormat(DATE_PATTERN).format(date);
        }
        return new SimpleDateFormat(PATTERN).format(date);
    }
}

 

然后看看效果吧:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM