java POI Excel导出功能

java 实体类,工具类
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.commons.utils.POIUtil;
import com.commons.vo.JSONMessage;
import com.wlsq.cloudpark.service.CloudParkingEntryRecordService;


@Controller
@RequestMapping("loginrecord")
public class ExcelRecordExport {
	
	@Resource
	private CloudParkingEntryRecordService cloudParkingRecordService;
	
	/**
	 * 记录导出
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("revenue_managent_down_export.htm")
	@ResponseBody
	public JSONMessage revenueManagementDownExport(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			JSONMessage jsonMessage = new JSONMessage();
			String homeName = request.getParameter("export_home_name");//文件名
			String parking_id = String.valueOf(request.getParameter("export_parking_id"));
	   		String pay_state = request.getParameter("export_pay_state");
	   		String start_time= request.getParameter("export_start_time");
	   		String end_time= request.getParameter("export_end_time");
	   		
			

			//创建表格头部
			List<Map<String, Object>> headInfoList = new ArrayList<Map<String, Object>>();
			Map<String, Object> itemMap = new HashMap<String, Object>();
			itemMap.put("title", "停车场");
			itemMap.put("columnWidth", 60);
			itemMap.put("dataKey", "XH1");
			headInfoList.add(itemMap);
			itemMap = new HashMap<String, Object>();
			itemMap.put("title", "车牌号");
			itemMap.put("columnWidth", 30);
			itemMap.put("dataKey", "XH2");
			headInfoList.add(itemMap);
			itemMap = new HashMap<String, Object>();
			itemMap.put("title", "卡号");
			itemMap.put("columnWidth", 40);
			itemMap.put("dataKey", "XH3");
			headInfoList.add(itemMap);

			
			Map<String, Object> maps = new HashMap<String, Object>();
			maps.put("pay_state", pay_state);
			maps.put("start_time", start_time);
			maps.put("end_time", end_time);
			if(parking_id !=null&&!parking_id.equals("")){
				maps.put("parking_id", parking_id);
			}
			List<Map<String,Object>> coc= cloudParkingRecordService.selectCloudParkEntryRecordMap(maps);
			
			
			// excel 导出功能【数据填充】
			List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
			Map<String, Object> dataItem = null;
			// 限制下载数量2000
			if (coc.size() > 2000) {
				jsonMessage.put("exportQuantity", coc.size());
				return jsonMessage;
			}
			for (int i = 0; i < coc.size(); i++) {
				dataItem = new HashMap<String, Object>();
				Map<String,Object> de = coc.get(i);
				dataItem.put("XH1", de.get("parking_name"));
				dataItem.put("XH2", de.get("car_no"));
				dataItem.put("XH3", de.get("flag_no"));
				dataList.add(i, dataItem);
			}
			String writePath = "";
			String file_name = homeName;
			String path = "export/" + file_name + ".xls";
			POIUtil poiUtil = new POIUtil();
			// 1.创建 Workbook
			HSSFWorkbook hssfWorkbook = poiUtil.getHSSFWorkbook();
			// 2.创建 Sheet
			HSSFSheet hssfSheet = poiUtil.getHSSFSheet(hssfWorkbook, file_name);
			hssfSheet.createFreezePane(0, 1);//冻结导出excel第一行
			
			// 3.写入 head
			poiUtil.writeHeader(hssfWorkbook, hssfSheet, headInfoList);
			// 4.写入内容
			poiUtil.writeContent(hssfWorkbook, hssfSheet, 1, headInfoList,
					dataList);
			// 5.保存文件到filePath中
			String realPath = request.getSession().getServletContext().getRealPath("/");
			File file1 = new File(realPath+ path.substring(0, path.lastIndexOf("/")));
			if (!file1.exists())
				file1.mkdirs();
			writePath = realPath + path;
			FileOutputStream out1 = new FileOutputStream(writePath);
			try {
				hssfWorkbook.write(out1);
				out1.close();
				jsonMessage.put("exportQuantity", coc.size());
				jsonMessage.put("path", path);
				jsonMessage.put("file_name", file_name);
				return jsonMessage;
			} catch (final Exception e) {
				e.printStackTrace();
				new Thread() {
					@Override
					public void run() {
						// 获取错误日志
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						e.printStackTrace(new PrintStream(baos));
					}
				}.start();
			}
		} catch (Exception e) {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			e.printStackTrace(new PrintStream(baos));
		}
		return null;
	}

	
	/**
	 * 获取导出的excel保存到本地服务器,获取地址下载
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("export_download.htm")
	public void exportDownload(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("utf-8");
		FileInputStream fis = null;
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			String path = new String(request.getParameter("path"));
			String srcName = new String(request.getParameter("src"));
			path = request.getSession().getServletContext().getRealPath("/" + path);
			String fileName = path.substring(path.lastIndexOf("/") + 1);
			String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
			response.reset();// 清空buffer,设置页面不缓存
			if (fileType.equals("xls") || fileType.equals("xlsx")) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/octet-stream");
				// 通常解决汉字乱码方法用URLEncoder.encode(...)
				String filenamedisplay = URLEncoder.encode(srcName, "UTF-8");
				if ("FF".equals(getBrowser(request))) {
					// 针对火狐浏览器处理方式不一样了
					filenamedisplay = new String(srcName.getBytes("UTF-8"),"iso-8859-1");
				}
				response.setHeader("Content-Disposition","attachment;filename=" + filenamedisplay + ".xls");
			}
			fis = new FileInputStream(path);
			bis = new BufferedInputStream(fis);
			os = response.getOutputStream();
			byte[] b = new byte[200];
			int size = bis.read(b);
			while (size > 0) {
				os.write(b, 0, size);
				size = bis.read(b);
			}
			os.flush();
			os.close();
			bis.close();
			fis.close();
			File file = new File(path);
			if (file.isFile() && file.exists()) {
				file.delete();
			}
		} catch (Exception e) {
			e.printStackTrace();
			// 获取错误日志
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			e.printStackTrace(new PrintStream(baos));
			try {
				os.close();
				bis.close();
				fis.close();
			} catch (Exception ex) {
			}
		}
	}
	
	// 以下为服务器端判断客户端浏览器类型的方法
		private String getBrowser(HttpServletRequest request) {
			String UserAgent = request.getHeader("USER-AGENT").toLowerCase();
			if (UserAgent != null) {
				if (UserAgent.indexOf("msie") >= 0)
					return "IE";
				if (UserAgent.indexOf("firefox") >= 0)
					return "FF";
				if (UserAgent.indexOf("safari") >= 0)
					return "SF";
			}
			return null;
		}
}

package com.commons.utils;

import org.apache.poi.hssf.usermodel.*;  

import java.io.FileOutputStream;  
import java.io.IOException;  
import java.util.Calendar;  
import java.util.List;  
import java.util.Map;  
  
/** 
 * poi 导出excel 工具类 
 */  
public class POIUtil {  
  
    /** 
     * 1.创建 workbook 
     * @return 
     */  
    public HSSFWorkbook getHSSFWorkbook(){  
        return new HSSFWorkbook();  
    }  
  
    /** 
     * 2.创建 sheet 
     * @param hssfWorkbook 
     * @param sheetName sheet 名称 
     * @return 
     */  
    public HSSFSheet getHSSFSheet(HSSFWorkbook hssfWorkbook, String sheetName){  
        return hssfWorkbook.createSheet(sheetName);  
    }  
  
    /** 
     * 3.写入表头信息 
     * @param hssfWorkbook 
     * @param hssfSheet 
     * @param headInfoList List<Map<String, Object>> 
     *              key: title         列标题 
     *                   columnWidth   列宽 
     *                   dataKey       列对应的 dataList item key 
     */  
    public void writeHeader(HSSFWorkbook hssfWorkbook,HSSFSheet hssfSheet ,List<Map<String, Object>> headInfoList){  
        HSSFCellStyle cs = hssfWorkbook.createCellStyle();  
        HSSFFont font = hssfWorkbook.createFont();  
        font.setFontHeightInPoints((short)12);  
        font.setBoldweight(font.BOLDWEIGHT_BOLD);  
        cs.setFont(font);  
        cs.setAlignment(cs.ALIGN_CENTER);  
  
        HSSFRow r = hssfSheet.createRow(0);  
        r.setHeight((short) 380);  
        HSSFCell c = null;  
        Map<String, Object> headInfo = null;  
        //处理excel表头  
        for(int i=0, len = headInfoList.size(); i < len; i++){  
            headInfo = headInfoList.get(i);  
            c = r.createCell(i);  
            c.setCellValue(headInfo.get("title").toString());  
            c.setCellStyle(cs);  
            if(headInfo.containsKey("columnWidth")){  
                hssfSheet.setColumnWidth(i, (short)(((Integer)headInfo.get("columnWidth") * 8) / ((double) 1 / 20)));  
            }  
        }  
    }  
  
    /** 
     * 4.写入内容部分 
     * @param hssfWorkbook 
     * @param hssfSheet 
     * @param startIndex 从1开始,多次调用需要加上前一次的dataList.size() 
     * @param headInfoList List<Map<String, Object>> 
     *              key: title         列标题 
     *                   columnWidth   列宽 
     *                   dataKey       列对应的 dataList item key 
     * @param dataList 
     */  
    public void writeContent(HSSFWorkbook hssfWorkbook,HSSFSheet hssfSheet ,int startIndex,  
                                     List<Map<String, Object>> headInfoList, List<Map<String, Object>> dataList){  
        Map<String, Object> headInfo = null;  
        HSSFRow r = null;  
        HSSFCell c = null;  
        //处理数据  
        Map<String, Object> dataItem = null;  
        Object v = null;  
        for (int i=0, rownum = startIndex, len = (startIndex + dataList.size()); rownum < len; i++,rownum++){  
            r = hssfSheet.createRow(rownum);  
            r.setHeightInPoints(16);  
            dataItem = dataList.get(i); 
            for(int j=0, jlen = headInfoList.size(); j < jlen; j++){  
                headInfo = headInfoList.get(j);  
                c = r.createCell(j);  
                v = dataItem.get(headInfo.get("dataKey").toString());  
                if (v instanceof String) {  
                    c.setCellValue((String)v);  
                }else if (v instanceof Boolean) {  
                    c.setCellValue((Boolean)v);  
                }else if (v instanceof Calendar) {  
                    c.setCellValue((Calendar)v);  
                }else if (v instanceof Double) {  
                    c.setCellValue((Double)v);  
                }else if (v instanceof Integer  
                        || v instanceof Long  
                        || v instanceof Short  
                        || v instanceof Float) {  
                    c.setCellValue(Double.parseDouble(v.toString()));  
                }else if (v instanceof HSSFRichTextString) {  
                    c.setCellValue((HSSFRichTextString)v);  
                }else {  
                	if(v == null){
                		c.setCellValue("");  
                	}else{
                		c.setCellValue(v.toString());  
                	}
                }  
            }  
        }  
    }  
  
    public void write2FilePath(HSSFWorkbook hssfWorkbook, String filePath) throws IOException{  
        FileOutputStream fileOut = null;  
        try{  
            fileOut = new FileOutputStream(filePath);  
            hssfWorkbook.write(fileOut);  
        }finally{  
            if(fileOut != null){  
                fileOut.close();  
            }  
        }  
    }  
  
  
    /** 
     * 导出excel 
     * code example: 
         List<Map<String, Object>> headInfoList = new ArrayList<Map<String,Object>>(); 
         Map<String, Object> itemMap = new HashMap<String, Object>(); 
         itemMap.put("title", "序号1"); 
         itemMap.put("columnWidth", 25); 
         itemMap.put("dataKey", "XH1"); 
         headInfoList.add(itemMap); 
 
         itemMap = new HashMap<String, Object>(); 
         itemMap.put("title", "序号2"); 
         itemMap.put("columnWidth", 50); 
         itemMap.put("dataKey", "XH2"); 
         headInfoList.add(itemMap); 
 
         itemMap = new HashMap<String, Object>(); 
         itemMap.put("title", "序号3"); 
         itemMap.put("columnWidth", 25); 
         itemMap.put("dataKey", "XH3"); 
         headInfoList.add(itemMap); 
 
         List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>(); 
         Map<String, Object> dataItem = null; 
         for(int i=0; i < 100; i++){ 
         dataItem = new HashMap<String, Object>(); 
         dataItem.put("XH1", "data" + i); 
         dataItem.put("XH2", 88888888f); 
         dataItem.put("XH3", "脉兜V5.."); 
         dataList.add(dataItem); 
         } 
         POIUtil.exportExcel2FilePath("test sheet 1","F:\\temp\\customer2.xls", headInfoList, dataList); 
 
     * @param sheetName   sheet名称 
     * @param filePath   文件存储路径, 如:f:/a.xls 
     * @param headInfoList List<Map<String, Object>> 
     *                           key: title         列标题 
     *                                columnWidth   列宽 
     *                                dataKey       列对应的 dataList item key 
     * @param dataList  List<Map<String, Object>> 导出的数据 
     * @throws java.io.IOException 
     * 
     */  
    public static void exportExcel2FilePath(String sheetName, String filePath,  
                                   List<Map<String, Object>> headInfoList,  
                                   List<Map<String, Object>> dataList) throws IOException {  
        POIUtil poiUtil = new POIUtil();  
        //1.创建 Workbook  
        HSSFWorkbook hssfWorkbook = poiUtil.getHSSFWorkbook();  
        //2.创建 Sheet  
        HSSFSheet hssfSheet = poiUtil.getHSSFSheet(hssfWorkbook, sheetName);  
        //3.写入 head  
        poiUtil.writeHeader(hssfWorkbook, hssfSheet, headInfoList);  
        //4.写入内容  
        poiUtil.writeContent(hssfWorkbook, hssfSheet, 1, headInfoList, dataList);  
        //5.保存文件到filePath中  
        poiUtil.write2FilePath(hssfWorkbook, filePath);  
    }  
  
}  

jsp页面:
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.form.js"></script>//不可缺少
<!-- 导出数据start -->
<form id="export_excel" action="" enctype="multipart/form-data" method="post">
	<input type="hidden" id="export_select_value" name="export_select_value">
	<input type="hidden" id="export_parking_id" name="export_parking_id" >
	<input type="hidden" id="export_time_type" name="export_time_type" >
	<input type="hidden" id="export_pay_state" name="export_pay_state" >
	<input type="hidden" id="export_parking_type" name="export_parking_type">
	<input type="hidden" id="export_start_time" name="export_start_time" >
	<input type="hidden" id="export_end_time" name="export_end_time">
	<input type="hidden" id="export_home_name" name="export_home_name">
</form>
<div class="ownerExport_div" style="height:200px;width: 500px;position: absolute;top: 30%;left: 40%;border: 1px solid #dddddd; background-color: #F8F8FF;z-index: 999999;padding-top:10ox;">
	<div class="bi_div_title">记录批量下载</div>
	<br>  
	<div style="text-align:center;">
		<span style="color:red;font-size:13px;">注意:一次性只能导出2000条信息。</span><br>
	</div>
	<div style="clear: both;"></div>
	<div class="ac_foot_div">
		<button class="owner_export_qr" style="">导出</button>
		<button class="owner_export_qx" style="width: 58px; height: 32px;border: 1px solid #ddd; margin-left: 10px;font-size: 12px;">取消</button>
	</div>
</div>
<!-- 导出数据end -->

js代码:
on("click",".owner_export_qr",function(){
									
		$("#export_start_time").val($("#search_start_date").val());
		$("#export_end_time").val($("#search_end_date").val());
		$("#export_parking_id").val($(".su_change_parking").val());
		$("#export_select_value").val($(".search_input").val());
		if($(".pay_state").val() != 0){
			$("#export_pay_state").val($(".pay_state").val());
		}else{
			$("#export_pay_state").val("");
		}
		if($(".parking_type").val() != 0){
			$("#export_parking_type").val($(".parking_type").val());
		}else{
			$("#export_parking_type").val("");
		}
		if($(".time_type").val() == 0){
			$("#export_time_type").val("");
		}else{
			$("#export_time_type").val($(".time_type").val());
		}
		$("#export_home_name").val("记录导出");
		
		$("#export_excel").ajaxSubmit({  
			url:'loginrecord/revenue_managent_down_export.htm',//后台请求路径
			  dataType: 'JSON',
			success:function(data){   
				var obj= data;
				$(".containers").css("display","none");
				//验证导出数据不能为空
				if(obj.exportQuantity<=0){
					swal({
						title: "操作提示:", 
						text: "请注意:没有可导出的数据", 
						type: "warning",
						showCancelButton: true,
						closeOnConfirm: true,
						confirmButtonText: "确认",
						confirmButtonColor: "#DD6B55",
						cancelButtonText: "关闭",
						}, function() {
						});	
				}else if(obj.exportQuantity>2000){
					swal({
						title: "操作提示:", 
						text: "请注意:导出数量超过2000条。", 
						type: "warning",
						showCancelButton: true,
						closeOnConfirm: true,
						confirmButtonText: "确认",
						confirmButtonColor: "#DD6B55",
						cancelButtonText: "关闭",
						}, function() {
						});	
				}else if(obj.exportQuantity<=2000 && obj.exportQuantity>0){
					//path后台请求下载文件路径,src:excel名称
					window.location.href="loginrecord/export_download.htm?path="+obj.path+"&src="+obj.file_name;
					swal({   
						title: "导出成功",   
						type: "success",
						timer: 3000,   
						showConfirmButton: false
					});
					window.setTimeout(function(){
						window.location.reload();
					}, 3100);
				}else{
					swal("操作失败", "数据异常,请刷新页面重试", "error");
				}
			},error:function errorMsg(){ 
				swal({   
					title: "操作提示:",
					text:"抱歉:网络故障,导出excel数据出现异常,请重新导出操作!",
					showCancelButton: true,
					closeOnConfirm: true,
					confirmButtonText: "确认",
					confirmButtonColor: "#DD6B55",
					cancelButtonText: "关闭",
					}, function(index) {
					   if(index==false||index==true){
							window.location.reload();
					   }
					});
				}
		});
}).on("click",".owner_export_qx",function(){
	$(".ownerExport_div").hide();
});



猜你喜欢

转载自blog.csdn.net/wanwei1987/article/details/78936317