使用POI 導出Excel 動態合並單元格


一、存儲單元格內容  行標  列標的實體類   PoiModel

package com.zsplat.qrcode.exportexcel.model;


/**
 * 
 * @ClassName:PoiModel
 * @Description:TODO(這里用一句話描述這個類的作用)
 * @author: ZHOUPAN
 * @date 2019年1月25日 下午3:10:30
 *
 * @Copyright: 2018 www.zsplat.com Inc. All rights reserved.
 */
public class PoiModel {
    
    //內容
    private String content;
    //上一行同一位置內容
    private String oldContent;
    //行標
    private int rowIndex;
    //列標
    private int cellIndex;
 
    public String getOldContent() {
        return oldContent;
    }
 
    public void setOldContent(String oldContent) {
        this.oldContent = oldContent;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
        this.content = content;
    }
 
    public int getRowIndex() {
        return rowIndex;
    }
 
    public void setRowIndex(int rowIndex) {
        this.rowIndex = rowIndex;
    }
 
    public int getCellIndex() {
        return cellIndex;
    }
 
    public void setCellIndex(int cellIndex) {
        this.cellIndex = cellIndex;
    }
}

二、導出Excel工具類

package com.zsplat.qrcode.commons.utils;


import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.google.common.collect.Lists;
import com.zsplat.qrcode.commons.utils.lang.DateUtils;
import com.zsplat.qrcode.exportexcel.model.PoiModel;

/**
 * 導出  動態合並單元格
 * @ClassName:ExportExcelByPoiUtil
 * @Description:TODO(這里用一句話描述這個類的作用)
 * @author: ZHOUPAN
 * @date 2019年1月25日 下午3:22:27
 *
 * @Copyright: 2018 www.zsplat.com Inc. All rights reserved.
 */
public class ExportExcelByPoiUtil {
    /**
     * 
     * @Title: createExcel 
     * @Description: TODO(這里用一句話描述這個方法的作用) 
     * @author: ZHOUPAN
     * @date: 2019年1月30日 下午4:37:01
     * @param @param request
     * @param @param response
     * @param @param title 標題數組
     * @param @param titleHead  Excel標題
     * @param @param widthAttr  單元格寬度
     * @param @param maps  數據
     * @param @param mergeIndex  要合並的列   數組
     * @param @return    設定文件 
     * @return String    返回類型 
     * @throws
     */
    @SuppressWarnings("rawtypes")
    public static String createExcel(HttpServletRequest request, HttpServletResponse response,String[] title,String titleHead ,int[] widthAttr,Map<String/*sheet名*/, List<Map<String/*對應title的值*/, String>>> maps, int[] mergeIndex){
        if (title.length==0){
            return null;
        }
        /*初始化excel模板*/
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = null;
        int n = 0;
        /*循環sheet頁*/
        for(Map.Entry<String, List<Map<String/*對應title的值*/, String>>> entry : maps.entrySet()){
            /*實例化sheet對象並且設置sheet名稱,book對象*/
            try {
                sheet = workbook.createSheet();
                workbook.setSheetName(n, entry.getKey());
                workbook.setSelectedTab(0);
            }catch (Exception e){
                e.printStackTrace();
            }
            // 設置樣式 頭 cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
            // 水平方向的對齊方式
            CellStyle cellStyle_head = style(0, workbook);
            // 導出時間
            CellStyle cellStyle_export = style(3, workbook);
            // 標題
            CellStyle cellStyle_title = style(1, workbook);
            // 正文
            CellStyle cellStyle = style(2, workbook);
            // 合並單元格CellRangeAddress構造參數依次表示起始行,截至行,起始列, 截至列
             CellRangeAddress c1 = new CellRangeAddress(0, 0, 0, title.length-1);
             sheet.addMergedRegion(c1);
             CellRangeAddress c2 = new CellRangeAddress(1, 1, 0, title.length-1);
             sheet.addMergedRegion(c2);
             // 在sheet里創建第一行,參數為行索引(excel的行),可以是0~65535之間的任何一個
            Row row0 = sheet.createRow(0);
            // 創建單元格(excel的單元格,參數為列索引,可以是0~255之間的任何一個
            Cell cell1 = row0.createCell(0);
            // 設置單元格內容 標題
            cell1.setCellValue("上海明華電力———" + titleHead + "一覽表");
            cell1.setCellStyle(cellStyle_head);
            // 設置合並單元格邊框
            setRegionStyle(sheet, c1, cellStyle_head);
            setRegionStyle(sheet, c2, cellStyle_export);
            // 設置列寬
            for (int i = 0; i < widthAttr.length; i++) {
                sheet.setColumnWidth((short) i, (short) widthAttr[i] * 200);
            }
            // 在sheet里創建第二行
            Row row1 = sheet.createRow(1);
            // 創建單元格(excel的單元格,參數為列索引,可以是0~255之間的任何一個
            Cell cell2 = row1.createCell(0);
            // 設置單元格內容 標題
            cell2.setCellValue("導出時間:" + DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            cell2.setCellStyle(cellStyle_export);
            /*初始化標題,填值標題行(第一行)*/
            Row row2 = sheet.createRow(2);
            for(int i = 0; i<title.length; i++){
                /*創建單元格,指定類型*/
                Cell cell_1 = row2.createCell(i, Cell.CELL_TYPE_STRING);
                //設置標題的值
                cell_1.setCellValue(title[i]);
                //設置標題樣式
                cell_1.setCellStyle(cellStyle_title);
            }
            /*得到當前sheet下的數據集合*/
            List<Map<String/*對應title的值*/, String>> list = entry.getValue();
            /*遍歷該數據集合*/
            List<PoiModel> poiModels = Lists.newArrayList();
            if(null!=workbook){
                Iterator iterator = list.iterator();
//                int index = 1;/*這里1是從excel的第二行開始,第一行已經塞入標題了*/
                int index = 3;/*這里3是從excel的第四行開始,前面幾行已經塞入標題了*/
                while (iterator.hasNext()){
                    Row row = sheet.createRow(index);
                    /*取得當前這行的map,該map中以key,value的形式存着這一行值*/
                    @SuppressWarnings("unchecked")
                    Map<String, String> map = (Map<String, String>)iterator.next();
                    /*循環列數,給當前行塞值*/
                    for(int i = 0; i<title.length; i++){
                        String old = "";
                        /*old存的是上一行統一位置的單元的值,第一行是最上一行了,所以從第二行開始記*/
                        if(index > 3){
                            old = poiModels.get(i)==null ? "":poiModels.get(i).getContent();
                        }
                        /*循環需要合並的列*/
                        for(int j = 0; j < mergeIndex.length; j++){
                            /* 因為標題行前還有2行  所以index從3開始    也就是第四行*/
                            if(index == 3){
                                /*記錄第一行的開始行和開始列*/
                                PoiModel poiModel = new PoiModel();
                                poiModel.setOldContent(map.get(title[i]));
                                poiModel.setContent(map.get(title[i]));
                                poiModel.setRowIndex(3);
                                poiModel.setCellIndex(i);
                                poiModels.add(poiModel);
                                break;
                            }else if(i > 0 && mergeIndex[j] == i){
                                /*這邊i>0也是因為第一列已經是最前一列了,只能從第二列開始*/
                                /*當前同一列的內容與上一行同一列不同時,把那以上的合並, 或者在當前元素一樣的情況下,前一列的元素並不一樣,這種情況也合並*/
                                /*如果不需要考慮當前行與上一行內容相同,但是它們的前一列內容不一樣則不合並的情況,把下面條件中||poiModels.get(i).getContent().equals(map.get(title[i])) && !poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1]))去掉就行*/
                                if(!poiModels.get(i).getContent().equals(map.get(title[i])) || poiModels.get(i).getContent().equals(map.get(title[i])) && !poiModels.get(i - 1).getOldContent().equals(map.get(title[i-1]))){
                                    /*當前行的當前列與上一行的當前列的內容不一致時,則把當前行以上的合並*/
                                    CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第二行開始*/, index - 1/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
                                    //在sheet里增加合並單元格
                                    sheet.addMergedRegion(cra);
                                    /*重新記錄該列的內容為當前內容,行標記改為當前行標記,列標記則為當前列*/
                                    poiModels.get(i).setContent(map.get(title[i]));
                                    poiModels.get(i).setRowIndex(index);
                                    poiModels.get(i).setCellIndex(i);
                                }
                            }
                            /*處理第一列的情況*/
                            if(mergeIndex[j] == i && i == 0 && !poiModels.get(i).getContent().equals(map.get(title[i]))){
                                /*當前行的當前列與上一行的當前列的內容不一致時,則把當前行以上的合並*/
                                CellRangeAddress cra=new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第二行開始*/, index - 1/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
                                //在sheet里增加合並單元格
                                sheet.addMergedRegion(cra);
                                /*重新記錄該列的內容為當前內容,行標記改為當前行標記*/
                                poiModels.get(i).setContent(map.get(title[i]));
                                poiModels.get(i).setRowIndex(index);
                                poiModels.get(i).setCellIndex(i);
                            }
 
                            /*最后一行沒有后續的行與之比較,所有當到最后一行時則直接合並對應列的相同內容  加2是因為標題行前面還有2行*/
                            if(mergeIndex[j] == i && index == list.size()+2){
                                CellRangeAddress cra = new CellRangeAddress(poiModels.get(i).getRowIndex()/*從第二行開始*/, index/*到第幾行*/, poiModels.get(i).getCellIndex()/*從某一列開始*/, poiModels.get(i).getCellIndex()/*到第幾列*/);
                                //在sheet里增加合並單元格
                                sheet.addMergedRegion(cra);
                            }
                        }
                        Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING);
                        cell.setCellValue(map.get(title[i]));
                        cell.setCellStyle(cellStyle);
                        /*在每一個單元格處理完成后,把這個單元格內容設置為old內容*/
                        poiModels.get(i).setOldContent(old);
                    }
                    index++;
                }
            }
            n++;
        }
        
        OutputStream out = null;
        String localPath = null;
        try {
            Calendar calendar1 = Calendar.getInstance();
            String cal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar1.getTime());
            out = response.getOutputStream();
            response.reset();//清空輸出流
            response.setHeader("Content-disposition", "attachment;filename=" + new String(titleHead.getBytes("gbk"), "iso8859-1") + cal + ".xlsx");// 設定輸出文件頭
            response.setContentType("application/vnd.ms-excel;charset=GBK");// 定義輸出類型
            workbook.write(out);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                out.flush();
                out.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return localPath;
    }
    
    /**
     * 
     * @Title: style 
     * @Description: TODO(樣式) 
     * @author: GMY
     * @date: 2018年5月9日 下午5:16:48
     * @param @return    設定文件  index 0:頭 1:標題 2:正文
     * @return HSSFCellStyle    返回類型  
     * @throws
     */
    public static CellStyle style(int index, Workbook workbook) {
        CellStyle cellStyle = null;
        if (index == 0) {
            // 設置頭部樣式
            cellStyle = workbook.createCellStyle();
            // 設置字體大小 位置
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 生成一個字體
            Font font = workbook.createFont();
            //設置字體
            font.setFontName("微軟雅黑");
            //字體顏色
            font.setColor(HSSFColor.BLACK.index);// HSSFColor.VIOLET.index
            font.setFontHeightInPoints((short) 12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體增粗
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);//背景白色
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setFont(font);
        }
        //標題
        if (index == 1) {
            cellStyle = workbook.createCellStyle();
            // 設置字體大小 位置
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 生成一個字體
            Font font_title = workbook.createFont();
            //設置字體
            font_title.setFontName("微軟雅黑");
            font_title.setColor(HSSFColor.BLACK.index);// HSSFColor.VIOLET.index
            //字體顏色
            font_title.setFontHeightInPoints((short) 10);
            font_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字體增粗
            cellStyle.setFillForegroundColor(HSSFColor.GREY_40_PERCENT.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            cellStyle.setFont(font_title);
        }
        //正文
        if (index == 2) {
            // 設置樣式
            cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            // 生成一個字體
            Font font_title = workbook.createFont();
            //設置字體
            font_title.setFontName("微軟雅黑");
//            cellStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
            cellStyle.setWrapText(true); // 自動換行
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);//背景白色
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        }
        //時間
        if (index == 3) {
            // 設置樣式
            cellStyle = workbook.createCellStyle();
            // 居中
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
            // 生成一個字體
            Font font_title = workbook.createFont();
            //設置字體
            font_title.setFontName("微軟雅黑");
            font_title.setColor(HSSFColor.BLACK.index);// HSSFColor.VIOLET.index
                                                        // //字體顏色
            font_title.setFontHeightInPoints((short) 10);
            font_title.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
            cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setFont(font_title);

        }
        if (index == 4) {
            // 設置樣式
            cellStyle = workbook.createCellStyle();
            // 居中
//            cellStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
        }
        return cellStyle;
    }
    /**
     * 
     * @Title: setRegionStyle 
     * @Description: TODO(合並單元格后邊框不顯示問題) 
     * @author: GMY
     * @date: 2018年5月10日 上午10:46:00
     * @param @param sheet
     * @param @param region
     * @param @param cs    設定文件 
     * @return void    返回類型 
     * @throws
     */
    public static void setRegionStyle(Sheet sheet, CellRangeAddress region, CellStyle cs) {
        for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
            Row row = CellUtil.getRow(i, sheet);
            for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
                Cell cell = CellUtil.getCell(row, (short) j);
                cell.setCellStyle(cs);
            }
        }
    }
}

三、實踐中調用  

(1)controller 中導出的方法

@ResponseBody
    @RequestMapping(value = "/exportSafeConfess", method = RequestMethod.POST, produces = {
            "application/json;charset=UTF-8" })
    public void exportSafeConfess(HttpServletRequest request, HttpServletResponse response) {
        // 獲取頁面時間參數
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        Map<String, Object> paramsValue = new HashMap<String, Object>();
        paramsValue.put("startTime", startTime);
        paramsValue.put("endTime", endTime);
        paramsValue.put("pageIndex", null);
        paramsValue.put("pageSize", null);
        List<SafeConfess> resultList = safeConfessService.querySafeConfessAndContent(paramsValue);
        String titleAttr[] = { "安全交底名稱", "部門名稱", "項目名稱", "項目編號", "項目負責人", "工作地點", "工作編號", "公司聯系人", "公司聯系方式", "廠方聯系人",
                "廠方聯系方式", "現場確認人員 ", "執行人", "執行時間", "現場試驗其它危險源辨識", "針對上述危險源制定的安全措施", "現場試驗其它環境因素識別", "針對上述環境因素的控制措施",
                "措施確認檢查人", "措施確認檢查時間", "控制措施內容", "控制措施結果", "技術措施內容", "技術措施結果", "試驗前檢查人", "試驗前檢查時間", "試驗前檢查內容",
                "試驗前檢查結果", "試驗中檢查人", "試驗中檢查時間", "試驗中檢查內容", "試驗中檢查結果", "試驗后檢查人", "試驗后檢查時間", "試驗后檢查內容", "試驗后檢查結果" };
        int widthAttr[] = { 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
                30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30 };
        String titleHead = "安全交底";
        List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
        for (SafeConfess safeConfess : resultList) {
            Map<String, String> temp = null;
            List<SafeConfessContent> safeConfessContentList = safeConfess.getSafeConfessContentList();
            if (safeConfessContentList.size() > 0) {
                for (SafeConfessContent safeConfessContent : safeConfessContentList) {
                    temp = new HashMap<String, String>();
                    temp.put("安全交底名稱", safeConfess.getSafeName());
                    temp.put("部門名稱", safeConfess.getDeptName());
                    temp.put("項目名稱", safeConfess.getProjectName());
                    temp.put("項目編號", safeConfess.getProjectNumber());
                    temp.put("項目負責人", safeConfess.getProjectPerson());
                    temp.put("工作地點", safeConfess.getWorkAddress());
                    temp.put("工作編號", safeConfess.getWorkNumber());
                    temp.put("公司聯系人", safeConfess.getCompanyPerson());
                    temp.put("公司聯系方式", safeConfess.getCompanyPhone());
                    temp.put("廠方聯系人", safeConfess.getFactoryPerson());
                    temp.put("廠方聯系方式", safeConfess.getFactoryPhone());
                    temp.put("現場確認人員", safeConfess.getSceneComfirmPer());
                    temp.put("執行人", safeConfess.getDangerManager());
                    temp.put("執行時間", safeConfess.getManagerTime());
                    temp.put("現場試驗其它危險源辨識", safeConfess.getDangerDiscern());
                    temp.put("針對上述危險源制定的安全措施", safeConfess.getDangerMeasures());
                    temp.put("現場試驗其它環境因素識別", safeConfess.getEnvironmentDiscren());
                    temp.put("針對上述環境因素的控制措施", safeConfess.getEnvironmentMeasures());
                    temp.put("措施確認檢查人", safeConfess.getComfirmCheckPerson());
                    temp.put("措施確認檢查時間", safeConfess.getComfirmCheckTime());
                    // 狀態0:安全及環境相關控制措施 1:技術措施 2:試驗前 3:試驗中 4:試驗后
                    if (safeConfessContent.getcStatus().equals("0")) {
                        temp.put("控制措施內容", safeConfessContent.getcContent());
                        temp.put("控制措施結果", getcCheckResult(safeConfessContent.getcCheckResult()));

                    } else if (safeConfessContent.getcStatus().equals("1")) {
                        temp.put("技術措施內容", safeConfessContent.getcContent());
                        temp.put("技術措施結果", getcCheckResult(safeConfessContent.getcCheckResult()));
                    } else if (safeConfessContent.getcStatus().equals("2")) {
                        temp.put("試驗前檢查人", safeConfess.getTestBeforePerson());
                        temp.put("試驗前檢查時間", safeConfess.getTestBeforeTime());
                        temp.put("試驗前檢查內容", safeConfessContent.getcContent());
                        temp.put("試驗前檢查結果", getcCheckResult(safeConfessContent.getcCheckResult()));
                    } else if (safeConfessContent.getcStatus().equals("3")) {
                        temp.put("試驗中檢查人", safeConfess.getTestPerson());
                        temp.put("試驗中檢查時間", safeConfess.getTestTime());
                        temp.put("試驗中檢查內容", safeConfessContent.getcContent());
                        temp.put("試驗中檢查結果", getcCheckResult(safeConfessContent.getcCheckResult()));
                    } else if (safeConfessContent.getcStatus().equals("4")) {
                        temp.put("試驗后檢查人", safeConfess.getTestAfterPerson());
                        temp.put("試驗后檢查時間", safeConfess.getTestAfterTime());
                        temp.put("試驗后檢查內容", safeConfessContent.getcContent());
                        temp.put("試驗后檢查結果", getcCheckResult(safeConfessContent.getcCheckResult()));
                    }
                    dataList.add(temp);
                }
            } else {
                temp = new HashMap<String, String>();
            }
        }
        Map<String/* 此處的key為每個sheet的名稱,一個excel中可能有多個sheet頁 */, List<Map<String/* 此處key對應每一列的標題 */, String>>/* 該list為每個sheet頁的數據 */> map = Maps
                .newHashMap();
        map.put("安全交底列表", dataList);
        ExportExcelByPoiUtil.createExcel(request, response, titleAttr, titleHead, widthAttr, map, new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 }/* 此處數組為需要合並的列,可能有的需求是只需要某些列里面相同內容合並 */);
    }

(2)js中

     /**
         * 下載excel
         */
        excelExport:function (){
            var startTime = jQuery('#startTime').val();
            var endTime = jQuery('#endTime').val();
            // 開始時間為空或/結束時間為空
            if (startTime == "" && endTime != "") {
                startTime = "1999-01-01";
            } else if (startTime != "" && endTime == "") {
                //獲取當前時間
                endTime = GetDateStrFromCurrentMiuntes(new Date());
            }
            var d1 = new Date(startTime.replace(/\-/g, "\/"));
            var d2 = new Date(endTime.replace(/\-/g, "\/"));
            if (startTime != "" && endTime != "" && d1 > d2) {
                alert("開始時間不能大於結束時間!");
                return false;
            }
            var form = jQuery("<form>");
            form.attr("style", "display:none");
            form.attr("target", "");
            form.attr("method", "post");
            form.attr("action", "exportController/exportSafeConfess");
            var inputl = jQuery("<input>");
            inputl.attr("type", "hidden");
            inputl.attr("value", startTime);
            inputl.attr("name", "startTime");

            var inputl_1 = jQuery("<input>");
            inputl_1.attr("type", "hidden");
            inputl_1.attr("value", endTime);
            inputl_1.attr("name", "endTime");
            jQuery("body").append(form);
            form.append(inputl);
            form.append(inputl_1);
            form.submit();
        },

在html中頁面調用js導出的方法

 


免責聲明!

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



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