SSM POI---导出(含工具类)

Controller

package com.jk.poiExcel.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jk.login.bean.TAtyUser;
import com.jk.login.service.ILoginService;
import com.jk.util.Const;
import com.jk.util.ExportExcelUtils;

@Controller
public class PoiExcelImportOrExport {

	@Autowired
	private ILoginService loginServiceImpl;
	
	/**
	 * <pre>exportExcel(生成单表execle)   
	 * 创建人:
	 * 创建时间:2017年10月27日 下午4:12:43    
	 * 修改人:      
	 * 修改时间:2017年10月27日 下午4:12:43    
	 * 修改备注: 
	 * @param request
	 * @return</pre>
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Map<String, String>  exportExcel(HttpServletRequest request){
		String title="用户信息表";//定义子工作表名称
		//type1--调用final自定义常量const的headtitil list已经加入了预定义的字段
		//List<String> headList =Const.headTitil;
		
		//type2--定义字段(也可以再定义一个实体类,通过循环add加入list)
		ArrayList<String> headList = new ArrayList<String>();
		headList.add("姓名");
		headList.add("登录名");
		headList.add("邮箱");
		headList.add("职务");
		
		List<TAtyUser> userList=loginServiceImpl.getAllUserList();//查询所有信息
		  
        Map<String, Object> excelMap = new HashMap<String, Object>();
        excelMap.put("title", title);
        excelMap.put("head", headList);
        excelMap.put("data", userList);
        Map<String, String> map=new HashMap<String, String>();
        try {
        	map=ExportExcelUtils.UserXXToExcel(excelMap, "userxx2017.xls", request);
        	System.err.println(map.get("url")+"===================");
		} catch (Exception e) {
			map.put("success", "fail");//ajax回调函数,用success的值判断是否弹框下载链接
			e.printStackTrace();
		}
		return map;
	}
	
	
	/**
	 * <pre>exportExcel2017(生成多个子工作表execle)   
	 * 创建人:
	 * 创建时间:2017年10月27日 下午4:13:00    
	 * 修改人:      
	 * 修改时间:2017年10月27日 下午4:13:00    
	 * 修改备注: 
	 * @param request
	 * @return</pre>
	 */
	@RequestMapping("exportExcel2017")
	@ResponseBody
	public Map<String, String>  exportExcel2017(HttpServletRequest request){
		Map<String, String> map=new HashMap<String, String>();
		List<String> headList =Const.headTitil;
        List<TAtyUser> userList=loginServiceImpl.getAllUserList();
        List<Map<String, Object>> listMap= new ArrayList<Map<String, Object>>();
        HSSFWorkbook workbook = new HSSFWorkbook();
        for (int i = 0; i < 3; i++) {
        	Map<String, Object> dataMap = new HashMap<String, Object>();
        	String title="用户信息表"+i;
        	dataMap.put("title", title);
        	dataMap.put("headList", headList);
        	dataMap.put("data", userList);
        	listMap.add(dataMap);
		}
        try {
        	map=ExportExcelUtils.exportUserInfo(listMap, request);
        	System.out.println(map.get("url"));
		} catch (Exception e) {
			map.put("success", "fail");
			e.printStackTrace();
		}
		return map;
	}
}
Util


package com.jk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.jam.provider.ResourcePath;

import com.jk.login.bean.TAtyUser;


/**
 * ExportExcelUtils
 * @author rd
 * @version 1.0
 *
 */
public class ExportExcelUtils  {
    /** 日志 */
    private static final Log log = LogFactory.getLog(ExportExcelUtils.class);

    /**
     * @Title: exportExcel
     * @Description: 导出Excel的方法
     * @author: evan @ 2017-08-01 
     * @param workbook 
     * @param sheetNum (sheet的位置,0表示第一个表格中的第一个sheet)
     * @param sheetTitle  (sheet的名称)
     * @param headers    (表格的标题)
     * @param result   (表格的数据)
     * @param out  (输出流)
     * @throws Exception
     */
    public static void exportExcel(HSSFWorkbook workbook, int sheetNum,
            String sheetTitle, List<Map<String, Object>> headers,
            List<Map<String, Object>> result, OutputStream out) throws Exception {
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetTitle);
        HSSFPalette customPalette = workbook.getCustomPalette();
        customPalette.setColorAtIndex((short) 9, (byte) (0xff & 47),
            (byte) (0xff & 121), (byte) (0xff & 164));
        customPalette.setColorAtIndex((short) 10, (byte) (0xff & 255),
            (byte) (0xff & 255), (byte) (0xff & 255));
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor((short) 9);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 14);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 指定当单元格内容显示不下时自动换行
        style.setWrapText(true);

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(39);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            Map<String, Object> filed = (Map<String, Object>) headers.get(i);
            String filedName = ObjectUtils.toString(filed.get("C_Name"));
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(filedName);
            cell.setCellValue(text.toString());
        }
        // 遍历集合数据,产生数据行
        int index = 1;
        HSSFCellStyle styledata = workbook.createCellStyle();
        HSSFFont fontdata = workbook.createFont();
        fontdata.setColor(HSSFColor.BLACK.index);
        fontdata.setFontHeightInPoints((short) 12);
        // 指定当单元格内容显示不下时自动换行
        styledata.setWrapText(true);
        styledata.setFont(fontdata);
        styledata.setFillForegroundColor((short) 10);
        styledata.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        styledata.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styledata.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        styledata.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        for (Map<String, Object> dataCell : result) {
            row = sheet.createRow(index);
            int cellIndex = 0;
            for (int i = 0; i < headers.size(); i++) {
                Map<String, Object> filed = (Map<String, Object>) headers
                        .get(i);
                String filedId = ObjectUtils.toString(filed.get("C_Field"));
                HSSFCell cell = row.createCell(cellIndex);
                cell.setCellValue(ObjectUtils.toString(dataCell.get(filedId)));
                cell.setCellStyle(styledata);
                cellIndex++;
            }
            index++;
        }
    }

   /**
    * <pre>exportUserxxExcel(bean中取出属性,定义列中字段)   
    * 创建人:
    * 创建时间:2017年10月27日 下午4:04:58    
    * 修改人:      
    * 修改时间:2017年10月27日 下午4:04:58    
    * 修改备注: 
    * @param workbook
    * @param sheetNum
    * @param sheetTitle
    * @param headers
    * @param result
    * @param out
    * @throws Exception</pre>
    */
    public static void exportUserxxExcel(HSSFWorkbook workbook, int sheetNum,
            String sheetTitle,  List<String> headers,
            List<TAtyUser> result, OutputStream out) throws Exception {
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetTitle);
        
        HSSFPalette customPalette = workbook.getCustomPalette();
        customPalette.setColorAtIndex((short) 9, (byte) (0xff & 47),
            (byte) (0xff & 121), (byte) (0xff & 164));
        customPalette.setColorAtIndex((short) 10, (byte) (0xff & 255),
            (byte) (0xff & 255), (byte) (0xff & 255));
        
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor((short) 9);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 14);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 指定当单元格内容显示不下时自动换行
        style.setWrapText(true);

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints(39);
        for (int i = 0; i < headers.size(); i++) {
            HSSFCell cell = row.createCell(i);
            String filedName = ObjectUtils.toString(headers.get(i));
            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(filedName);
            cell.setCellValue(text.toString());
        }
        // 遍历集合数据,产生数据行
        int index = 1;
        HSSFCellStyle styledata = workbook.createCellStyle();
        HSSFFont fontdata = workbook.createFont();
        fontdata.setColor(HSSFColor.BLACK.index);
        fontdata.setFontHeightInPoints((short) 12);
        // 指定当单元格内容显示不下时自动换行
        styledata.setWrapText(true);
        styledata.setFont(fontdata);
        styledata.setFillForegroundColor((short) 10);
        styledata.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        styledata.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styledata.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styledata.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        styledata.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        
        //定义表头中要加入bean中的哪些字段
        for (TAtyUser dataCell : result) {
            row = sheet.createRow(index);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue(ObjectUtils.toString(dataCell.getcName()));
            cell.setCellStyle(styledata);
            HSSFCell cell2 = row.createCell(1);
            cell2.setCellValue(ObjectUtils.toString(dataCell.getcLoginid()));
            cell2.setCellStyle(styledata);
            HSSFCell cell3 = row.createCell(2);
            cell3.setCellValue(ObjectUtils.toString(dataCell.getcMail()));
            cell3.setCellStyle(styledata);
            HSSFCell cell4 = row.createCell(3);
            cell4.setCellValue(ObjectUtils.toString(dataCell.getcPassword()));
            cell4.setCellStyle(styledata);
            index++;
        }
    }
	 /**
	  * <pre>exportUserxx()   
	  * 创建人:
	  * 创建时间:2017年10月27日 下午3:51:55    
	  * 修改人:     
	  * 修改时间:2017年10月27日 下午3:51:55    
	  * 修改备注: 
	  * @param workbook
	  * @param sheetNum
	  * @param sheetTitle
	  * @param headers
	  * @param result
	  * @throws Exception</pre>
	  */
    public static void exportUserxx(HSSFWorkbook workbook, int sheetNum,
            String sheetTitle,  List<String> headers,
            List<TAtyUser> result) throws Exception {
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetTitle);
        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        
        for (int i = 0; i < headers.size(); i++) {
        	 HSSFCell cell = row.createCell(i);
        	 cell.setCellValue(headers.get(i));
		}
        
        for (int i = 0; i < result.size(); i++){
        	    TAtyUser user=result.get(i);
        	    HSSFRow rowdata = sheet.createRow(i+1);
        		HSSFCell cell1=rowdata.createCell(0);
        		cell1.setCellValue(user.getcName());
        		HSSFCell cell2=rowdata.createCell(1);
           		cell2.setCellValue(user.getcLoginid());
           		HSSFCell cell3=rowdata.createCell(2);
       		    cell3.setCellValue(user.getcMail());
       		    HSSFCell cell4=rowdata.createCell(3);
   		       cell4.setCellValue(user.getUserpost());
        }
        
    }
    /**
     * 用于导出反馈结果页面的Excel
     * @param dataList 数据List
     * @param fileName 导出文件Excel
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> fkqrToExcel(
            List<Map<String, Object>> dataList, String fileName, HttpServletRequest request) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
        	//
            String filePath = request.getSession().getServletContext().getRealPath("/fkjgExcel");
            File tempDir = new File(filePath);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            OutputStream out = new FileOutputStream(filePath + fileName);
            HSSFWorkbook workbook = new HSSFWorkbook();
            int i = 0;
            for (Map<String, Object> map : dataList) {
                String sheetName = ObjectUtils.toString(map.get("sheetName"));
                List<Map<String, Object>> data = (List<Map<String, Object>>) map
                        .get("resdata");
                List<Map<String, Object>> filedName = (List<Map<String, Object>>) map
                        .get("lbFiled");
                if (filedName != null
                        && data != null) {
                    exportExcel(workbook, i++, sheetName, filedName, data, out);
                }
            }
            if (i == 0) {
                HSSFSheet sheet = workbook.createSheet();
                workbook.setSheetName(0, "暂无数据");
                HSSFRow row = sheet.createRow(0);
                row.createCell(0);
            }
            workbook.write(out);
            out.close();
            resultMap.put("success", "ok");
        } catch (FileNotFoundException e) {
            log.error("ExportExcelUtils===生成EXCEL文件失败。");
            resultMap.put("success", "fail");
        }
        return resultMap;
    }
    /**
     * 用于导出反馈结果页面的Excel
     * @param dataList 数据List
     * @param fileName 导出文件Excel
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> UserXXToExcel(Map<String, Object> dataMap,
             String fileName , HttpServletRequest request) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        String contextPath = request.getContextPath(); 
        //获取项目的访问路径 http://localhost:8080/shixun05c/
        String url=request.getScheme()+"://"+request.getServerName()+":"+
                request.getServerPort()+contextPath+"/";
        try {
        	//生成Excel要存放的服务器路径
            String filePath =  request.getSession().getServletContext().getRealPath("/fkjgExcel");;
            File tempDir = new File(filePath);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            OutputStream out = new FileOutputStream(filePath +"\\"+ fileName);
            
            //这种声明方式只是导出.xls Excel文件工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //这种声明方式只是导出.xlsx Excel文件工作簿
            //XSSFWorkbook workbookXl=new XSSFWorkbook();
            String sheetName=(String) dataMap.get("title");
            List<TAtyUser> data=(List<TAtyUser>) dataMap.get("data");
            List<String> head=(List<String>) dataMap.get("head");
            exportUserxxExcel(workbook, 0, sheetName, head, data, out);
            
            if (dataMap == null) {
                HSSFSheet sheet = workbook.createSheet();
                workbook.setSheetName(0, "暂无数据");
                HSSFRow row = sheet.createRow(0);
                row.createCell(0);
            }
            workbook.write(out);
            out.close();
            resultMap.put("success", "ok");
            resultMap.put("url",url+"/fkjgExcel/"+fileName);
        } catch (FileNotFoundException e) {
            log.error("ExportExcelUtils===生成EXCEL文件失败。");
            resultMap.put("success", "fail");
        }
        return resultMap;
    }
    /**
     * 用于查看详情页面的导出Excel
     * @param dataList 数据List
     * @param fileName 导出文件Excel
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static Map<String, String> ckxqToExcel(
            List<Map<String, Object>> dataList, String fileName, HttpServletRequest request) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        try {
            String filePath = request.getSession().getServletContext().getRealPath("/fkjgExcel");
            File tempDir = new File(filePath);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            OutputStream out = new FileOutputStream(filePath + fileName);
            HSSFWorkbook workbook = new HSSFWorkbook();
            Map<String, Object> styleMap = createStyle(workbook);
            HSSFSheet sheet = workbook.createSheet();
            sheet.setDefaultColumnWidth(30);
            HSSFRow row = null;
            int rowNum = 0;
            if (dataList != null && dataList.size() != 0) {
                for (int dataC = 0; dataC < dataList.size(); dataC++) {
                    Map<String, Object> dataMap = dataList.get(dataC);
                    String title = ObjectUtils.toString(dataMap.get("title"));
                    List<Map<String, Object>> tableData = (List<Map<String, Object>>) dataMap
                            .get("data");
                    rowNum = exportExcelTitle(sheet, title, rowNum, styleMap,
                        row);
                    rowNum = exportExcelTableData(sheet, tableData, rowNum,
                        styleMap, row);
                }
            }
            workbook.write(out);
            out.close();
        } catch (Exception e) {
        }

        return resultMap;
    }

    /**
     * 将结果数据写入到EXCEL的表中
     * @param sheet
     * @param data
     * @param rowNum
     * @param style
     * @param row
     * @return
     */
    public static int exportExcelTableData(HSSFSheet sheet,
            List<Map<String, Object>> data, int rowNum,
            Map<String, Object> style, HSSFRow row) {
        HSSFCellStyle styleFCommon = (HSSFCellStyle) style.get("styleFCommon");
        HSSFCellStyle styleDCommon = (HSSFCellStyle) style.get("styleDCommon");
        int size = data.size();
        int ys = size % 3;
        int zs = size / 3;
        int rowCount = 0;
        if (ys == 0) {
            rowCount = zs;
        } else {
            rowCount = zs + 1;
        }
        int cellCount = 0;
        for (int i = rowNum; i < rowNum + rowCount; i++) {
            row = sheet.createRow(i);
            row.setHeightInPoints(39);
            int cellIndex = 0;
            for (int dj = 0; dj < 3; dj++) {
                if (cellCount < size) {
                    HSSFCell cellName = row.createCell(cellIndex);
                    Map<String, Object> dataMap = data.get(cellCount);
                    String name = ObjectUtils.toString(dataMap.get("name"));
                    cellName.setCellValue(name);
                    cellName.setCellStyle(styleFCommon);
                    cellIndex++;
                    HSSFCell cellvalue = row.createCell(cellIndex);
                    String value = ObjectUtils.toString(dataMap.get("value"));
                    cellvalue.setCellValue(value);
                    cellvalue.setCellStyle(styleDCommon);
                    cellIndex++;
                    cellCount++;
                } else {
                    break;
                }

            }
        }
        return rowNum + rowCount;
    }

    /**
     * 给每一个表单增加title
     * @param sheet
     * @param title
     * @param rowNum
     * @param style
     * @param row
     * @return
     */
    @SuppressWarnings("deprecation")
    public static int exportExcelTitle(HSSFSheet sheet, String title,
            int rowNum, Map<String, Object> style, HSSFRow row) {
        // 产生表格标题行
        HSSFCellStyle styleTitle = (HSSFCellStyle) style.get("styleTitle");
        row = sheet.createRow(rowNum);
        row.setHeightInPoints(39);
        HSSFCell cell0 = row.createCell(0);
        row.createCell(1).setCellStyle(styleTitle);
        row.createCell(2).setCellStyle(styleTitle);
        row.createCell(3).setCellStyle(styleTitle);
        row.createCell(4).setCellStyle(styleTitle);
        row.createCell(5).setCellStyle(styleTitle);
        cell0.setCellValue(title);
        cell0.setCellStyle(styleTitle);
        sheet.addMergedRegion(new CellRangeAddress(rowNum, rowNum, 0, 5));
        return rowNum + 1;
    }

    /**
     * 增加EXCEL展示所用的样式
     * @param workbook
     * @return
     */
    public static Map<String, Object> createStyle(HSSFWorkbook workbook) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        HSSFPalette customPalette = workbook.getCustomPalette();
        customPalette.setColorAtIndex((short) 9, (byte) (0xff & 67),
            (byte) (0xff & 146), (byte) (0xff & 217));
        customPalette.setColorAtIndex((short) 10, (byte) (0xff & 240),
            (byte) (0xff & 245), (byte) (0xff & 247));
        customPalette.setColorAtIndex((short) 11, (byte) (0xff & 251),
            (byte) (0xff & 252), (byte) (0xff & 253));
        // 通用样式数据行生成一个样式
        HSSFCellStyle styleFCommon = workbook.createCellStyle();
        styleFCommon.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        styleFCommon.setFillForegroundColor((short) 10);
        styleFCommon.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleFCommon.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styleFCommon.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styleFCommon.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styleFCommon.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
        styleFCommon.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        styleFCommon.setWrapText(true);
        // 通用生成一个字体
        HSSFFont fontCommon = workbook.createFont();
        fontCommon.setFontHeightInPoints((short) 14);
        styleFCommon.setFont(fontCommon);
        resultMap.put("styleFCommon", styleFCommon);
        // 通用样式字段名称li生成一个样式
        HSSFCellStyle styleDCommon = workbook.createCellStyle();
        styleDCommon.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        styleDCommon.setFillForegroundColor((short) 11);
        styleDCommon.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDCommon.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styleDCommon.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styleDCommon.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styleDCommon.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        styleDCommon.setWrapText(true);
        styleDCommon.setFont(fontCommon);
        resultMap.put("styleDCommon", styleDCommon);
        // TITLE样式生成一个样式HSSFCellStyle.VERTICAL_CENTER
        HSSFCellStyle styleTitle = workbook.createCellStyle();
        styleTitle.setFillForegroundColor((short) 9);
        styleTitle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        styleTitle.setWrapText(true);
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // TILTEL通用生成一个字体
        HSSFFont fontTiltl = workbook.createFont();
        fontTiltl.setColor(HSSFColor.BLACK.index);
        fontTiltl.setFontHeightInPoints((short) 16);
        fontTiltl.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        styleTitle.setFont(fontTiltl);
        resultMap.put("styleTitle", styleTitle);
        return resultMap;
    }
    
    /**
     * 现在Excel
     * @param fileName
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Object download(String fileName, HttpServletRequest request) {
        Map result = new HashMap();
        try {
            String fileurl = request.getSession().getServletContext().getRealPath("/fkjgExcel");
            byte[] fileData = null;
            FileInputStream fis = new FileInputStream(fileurl);
            fileData = new byte[fis.available()];
            fis.read(fileData);
            result.put("name", fileName.replaceAll("\\s*", ""));
            result.put("data", fileData);
            fis.close();
        } catch (Exception e) {
            log.error("文件下载失败!!");
        }
        return result;
    }
    
    public static Map<String,String> exportUserInfo(List<Map<String,Object>> datamap, HttpServletRequest request ){
    	
    	Map<String, String> resultMap = new HashMap<String, String>();
    	
    	//项目名称
    	 String contextPath = request.getContextPath(); 
        //获取项目的访问路径
        String url=request.getScheme()+"://"+request.getServerName()+":"+
                request.getServerPort()+contextPath+"/";
        try {
        	//获取文件存放路径
            String filePath = request.getSession().getServletContext().getRealPath("/fkjgExcel");
            File tempDir = new File(filePath);
            if (!tempDir.exists()) {
                tempDir.mkdirs();
            }
            OutputStream out = new FileOutputStream(filePath +"\\"+ "2017271026.xls");
            
            //这种声明方式只是导出.xls Excel文件工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            //这种声明方式只是导出.xlsx Excel文件
            //XSSFWorkbook workbookXl=new XSSFWorkbook();
            int i=0;
        	for (Map<String, Object> map : datamap) {
    			String sheetName=(String) map.get("title");
    			List<String> headList=(List<String>) map.get("headList");
    			List<TAtyUser> data= (List<TAtyUser>) map.get("data");
    			exportUserxx(workbook, i++, sheetName, headList, data);
    		}
        	 workbook.write(out);
             out.close();
             resultMap.put("success", "ok");
             resultMap.put("url", url+"/fkjgExcel/"+"2017271026.xls");
        }catch (FileNotFoundException e) {
            log.error("ExportExcelUtils===生成EXCEL文件失败。");
            resultMap.put("success", "fail");
        } catch (Exception e) {
			e.printStackTrace();
		}
        	
    	return resultMap;
    }
}

Service/Mapper只是查询了一个单表而已,就不上传了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值