列表导出excel,excel有固定模板,poi

excel有固定模板样式,列表导出excel

前台页面

<div style="float:right;margin-bottom:4px;">
                <button class="btn btn-default" type="button" onclick="export1('${formData.infoId!''}')"><i class="icon icon-file-excel"></i> 导出</button>
                <button class="btn btn-default" type="button" onclick="JavaScript :history.back(-1)"><i class="icon icon-reply"></i> 返回</button>

</div> 

js方法

 <script type="text/javascript">
        function export1(id){
            location.href = "${_b}/msg/msgBaseInfo/exportExcel?id="+id;
        }
 </script>

 controller 内容

@RequestMapping(value = "/exportExcel", method ={RequestMethod.GET,RequestMethod.POST })
    public void exportExcel(String id,
            HttpServletRequest request,HttpServletResponse response, ModelMap model) {
        EntityWrapper<MsgRecevier> entityWrapper = new EntityWrapper<MsgRecevier>();
        entityWrapper.eq("INFO_ID", id);
        List<MsgRecevier> msgReceviersList = msgRecevierServiceImpl.selectList(entityWrapper);
        MsgBaseInfo msgBaseInfo = msgBaseInfoServiceImpl.selectById(id);
        String isreport = msgBaseInfo.getIsReport();
        
        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        int i = 0;
        for(MsgRecevier m : msgReceviersList){
            @SuppressWarnings("unchecked")
            Map<String,Object> data = new BeanMap(m);
            Map<String,Object> newData = new HashMap<String,Object>();
            newData.putAll(data);
            i++;
            newData.put("xh", "" + i);
            resultList.add(newData);
        }
        if(isreport.equals("0")){
            ExportUtil.export(request, response, resultList,"签到表","noReport", 0, 2, 0, 2);
        }else{
            ExportUtil.export(request, response, resultList,"签到表","Report", 0, 2, 0, 3);
        }
        
    }

ExcelUtil

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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;
import org.apache.poi.ss.usermodel.CellStyle;

public class ExcelUtil {

    public static void main(String args[]) throws FileNotFoundException, IOException {
        List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("A", "1");
        dataMap.put("B", "2");
        dataMap.put("C", "3");
        dataList.add(dataMap);
        dataList.add(dataMap);
        dataList.add(dataMap);
        dataList.add(dataMap);
        HSSFWorkbook excel = generateExcel(dataList, "D:/1.xls", 0, 0, 0, 3);
        excel.write(new FileOutputStream("D:/2.xls"));
    }

    // 读写xls和xlsx格式时,HSSFWorkbook针对xls,XSSFWorkbook针对xlsx
    public static HSSFWorkbook generateExcel(List<Map<String, Object>> dataList, String template,// 模板路径
        int numSheet,// 第几个工作簿
        int startRow,// 开始行号,即记录变量的行号。起始为0
        int xStart, int xEnd) {
        InputStream is = null;
        HSSFWorkbook excel = null;
        try {
            is = new FileInputStream(template);
            excel = new HSSFWorkbook(is);
            HSSFSheet xssfSheet = excel.getSheetAt(numSheet);
            HSSFRow row = xssfSheet.getRow(startRow);

            for (int i = 0; i < dataList.size(); i++) {
                Map<String, Object> data = dataList.get(i);
                //HSSFRow tempRow = xssfSheet.createRow((short) (startRow + i + 1));
                HSSFRow tempRow = xssfSheet.getRow(startRow + i + 1);
//                if (row.getRowStyle() != null)
//                    tempRow.setRowStyle(row.getRowStyle());
                for (int j = xStart; j < xEnd; j++) {
                    if (row.getCell(j) != null) {
                        HSSFCell cell = row.getCell(j);
                        String key = cell.getStringCellValue();
                        //key = key.substring(2, key.length() - 1);
                        if (data.containsKey(key)) {
                            String value = "";
                            if (data.get(key) != null && !"".equals(key)) {
                                value = data.get(key).toString();
                            }
                            HSSFCell c = tempRow.createCell((short) j);
                            HSSFCellStyle cellStyle= cell.getCellStyle();  
                            //cellStyle.setBorderTop(CellStyle.BORDER_THIN);
                            cellStyle.setWrapText(true);    
                            c.setCellStyle(cellStyle);
                            c.setCellValue(new HSSFRichTextString(value));
                        }
                    }
                }
            }
            xssfSheet.shiftRows(startRow + 1, xssfSheet.getLastRowNum(), -1);
            // HSSFRow lastRow = xssfSheet.getRow(xssfSheet.getLastRowNum());
            // for (int j = xStart; j < xEnd; j++) {
            // HSSFCell cell = lastRow.getCell(j);
            // cell.setCellStyle(null);
            // }
            xssfSheet.removeRow(xssfSheet.getRow(xssfSheet.getLastRowNum() + 1));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return excel;
    }

    public static HSSFWorkbook generateExcel(List dataList, String filePath,
        Map<String, Object> dataMap) {
        // TODO Auto-generated method stub
        InputStream is = null;
        HSSFWorkbook excel = null;
        try {
            is = new FileInputStream(filePath);
            excel = new HSSFWorkbook(is);
            HSSFSheet xssfSheet = excel.getSheetAt(0);
            int rownum = 0;
            int lastRow = xssfSheet.getLastRowNum();
            for (int row = 0; row < lastRow; row++) {
                HSSFRow rowExcl = xssfSheet.getRow(row);
                for (int i = 0; i < rowExcl.getLastCellNum(); i++) {
                    HSSFCell cell = rowExcl.getCell(i);
                    String key ="";
                    try{
                    key = cell.getStringCellValue();
                    }catch (Exception e) {
                        // TODO: handle exception
                    }
                    if (!"".equals(key) && key != null) {
                        if (key.indexOf("&[") !=-1) {
                            key = key.substring(2, key.length() - 1);
                            String value = "";
                            if (dataMap.get(key) != null && !"".equals(key)) {
                                value = dataMap.get(key).toString();
                            }
                            cell.setCellValue(value);
                        }
                        if (key.indexOf("&{") !=-1) {
                            rownum = row;
                            break;
                        }
                    }
                }

            }
            if (rownum != 0 && dataList.size() > 0) {
                HSSFRow row = xssfSheet.getRow(rownum);
                for (int i = 0; i < dataList.size(); i++) {
                    Map<String, Object> data = (Map<String, Object>) dataList.get(i);
                    HSSFRow tempRow = xssfSheet.createRow((short) (rownum + i));
                    if (row.getRowStyle() != null)
                        tempRow.setRowStyle(row.getRowStyle());
                    for (int j = 0; j < 30; j++) {
                        if (row.getCell(j) != null) {
                            HSSFCell cell = row.getCell(j);
                            String key ="";
                            try{
                            key = cell.getStringCellValue();
                            key = key.substring(2, key.length() - 1);
                            }catch (Exception e) {
                                // TODO: handle exception
                            }
                            if (data.containsKey(key)&&!"".equals(key)) {
                                String value = "";
                                if (data.get(key) != null && !"".equals(key)) {
                                    value = data.get(key).toString();
                                }
                                HSSFCell c = tempRow.createCell((short) j);
                                c.setCellStyle(cell.getCellStyle());
                                c.setCellValue(value);
                            }
                        }
                    }
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return excel;
    }
}


ExportUtil

package com.newhero.product.module.msg.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

public class ExportUtil {
    
    @SuppressWarnings("rawtypes")
    public static void export(
            HttpServletRequest request,
            HttpServletResponse response,
            List dataList, String fileName,String templateName, int numSheet, int startRow, int xStart, int xEnd){

        response.reset();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String dateStr = sdf.format(new Date());
        fileName += "-" + dateStr;
        try {
            fileName = new String(fileName.getBytes(),"ISO-8859-1");
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 指定下载的文件名
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + ".xls" + "\"");
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
//        String basePrintPath = (String) request.getSession().getAttribute("basePrintPath");
        String basePrintPath = request.getRealPath("") + "/print/";
        String template = basePrintPath + templateName + ".xls";
        
        @SuppressWarnings("unchecked")
        HSSFWorkbook exportExcel = ExcelUtil.generateExcel(dataList, template, numSheet, startRow, xStart, xEnd);
        
        try {
            exportExcel.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}





注意的几点

1.excel模板中字段的名称,要与导出的map键的名称相同一致

2.模板.xls结尾,因为其中涉及版本不同的问题,.xlsx会报错。


猜你喜欢

转载自blog.csdn.net/qq543539043/article/details/79467872