java导出excel,txt

导出excel

1、获取数据,分装数据,调用下载工具类

$(document).on('click','.i_tri_exportKefu',function(event){
				//<a href="${pageContext.request.contextPath}/op/appServer/jumpToAppServiceExports.shtml" class="btn btn-info"><em>导出</em></a>
				var customerName = $("#customerNameId").val();
				var gameName = $("#gameNameId").val();
				var type = $("#typeId").val();//普通1、平台vip2、专属vip游戏客服3
				window.location.href = '${pageContext.request.contextPath}/op/appServer/jumpToAppServiceExports.shtml?customerName='+ customerName 
				+"&gameName="+gameName+"&type="+type ;
			});


/**
	 * 下载excel
	 * 
	 * @param mcAppreport
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 */
	@RequestMapping("/jumpToAppServiceExports")
	public void jumpToAppServiceExports(Model model, HttpServletResponse response,
			CustomerServiceAgent customerServiceAgent,
			String customerName,String gameName,String type)
			throws UnsupportedEncodingException {
		//1获取数据
		customerServiceAgent.setName(customerName);
		customerServiceAgent.setGamename(gameName);
		if(null != type && "" != type && !type.equals("0")){
			customerServiceAgent.setType(Integer.parseInt(type));
		}
		List<CustomerServiceAgent> customerServiceAgentList = new ArrayList<CustomerServiceAgent>();
		if(null != gameName && "" != gameName){
			customerServiceAgentList = customerService.queryCustomerServiceList(customerServiceAgent);
		}else{
			//customerServiceAgentList = customerService.queryCustomerServiceList2(customerServiceAgent);
		}
		//2导出excel名称
		String excelName = "客服人员";
		//3表头
		String[] excelHeader = { "客服人员id", "客服名称", "客服类型", "操作人员id", "创建时间"};
		//4分装数据写入实体数据
		Map<Integer, String[]> hashMap = new HashMap<Integer, String[]>();
		if (null != customerServiceAgentList && customerServiceAgentList.size() > 0) {
			for (int i = 0; i < customerServiceAgentList.size(); i++) {
				//String[] excelHeader = { "客服人员id", "客服名称", "客服类型", "操作人员id", "创建时间"};
				CustomerServiceAgent mcap = customerServiceAgentList.get(i);
				String[] rowValue = new String[mcap.getClass().getDeclaredFields().length];
				rowValue[0] = String.valueOf(mcap.getId());
				rowValue[1] = mcap.getName();
				//客服类型(普通1、平台vip2、专属vip游戏客服3)
				if (mcap.getType() == 3) {
					rowValue[2] = "专属VIP游戏客服";
				} else if (mcap.getType() == 2){
					rowValue[2] = "平台VIP客服";
				} else {
					rowValue[2] = "普通客服";
				}
				
				rowValue[3] = String.valueOf(mcap.getOperator());
				rowValue[4] = DateUtil.dateToStringWithTime(mcap.getCreatetime());
				hashMap.put(i, rowValue);
			}
		}
		
		//调用导出方法
		ExportExcelUtil.exportExcel(response, excelName, excelHeader, hashMap);
	}

2、用工具类下载excel

package com.sojson.common.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExportExcelUtil { 
	// 设置好账号的ACCESS_KEY和SECRET_KEY

	public static void exportExcel(HttpServletResponse response,String excelName,
			String[] excelHeader,Map<Integer, String[]> hashMap) {
		// 第一步,创建一个webbook,对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();

		// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet(excelName);

		// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);

		// 第四步,创建单元格,并设置值表头 设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		
		for (int i = 0; i < excelHeader.length; i++) {  
			HSSFCell cell = row.createCell(i);  
			cell.setCellValue(excelHeader[i]);  
			cell.setCellStyle(style);  
		}
		
		// 第五步,写入实体数据
		if (null != hashMap && hashMap.size() > 0) {
			for (int i = 0; i < hashMap.size(); i++) {
				row = sheet.createRow((int) i + 1);
				String[] strings = hashMap.get(i);
				for (int j = 0; j < strings.length; j++) {
					row.createCell((short) j).setCellValue(strings[j]);//累计用户数
				}
			}
		}
		

		// 第六步,通过response返回进行下载
		try {
			response.setHeader("Content-Disposition",
					"attachment;filename=" + new String((excelName + ".xls").getBytes("utf-8"), "iso-8859-1"));
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		response.setContentType("application/ms-excel;charset=UTF-8");

		OutputStream os = null;
		try {
			os = response.getOutputStream();
			wb.write(os);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}



导出txt

//导出串号
	$(document).on("click",".i_downLoad",function(event){
		event.preventDefault();
		
		var id = $(this).parent().attr("id");
		
		window.location.href = '${pageContext.request.contextPath}/op/gift/jumpToDownNumber.shtml?id='+ id ;
	});

@RequestMapping("/jumpToDownNumber")
	public void  jumpToDownNumber(String id, HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException{
		Gift gift = giftManagerService.queryGiftInfo(Integer.parseInt(id));
		
		response.setContentType("text/plain");  
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String name = simpleDateFormat.format(new Date());
        String fileName = URLEncoder.encode("礼包剩余串号"+ name, "UTF-8");    
        response.setHeader("Content-Disposition","attachment; filename=" + fileName + ".txt");    
        String result=gift.getExporpath();  
        System.out.println(result);  
        BufferedOutputStream buff = null;       
        StringBuffer write = new StringBuffer();       
        String enter = "\r\n";       
        ServletOutputStream outSTr = null;       
        try {       
             outSTr = response.getOutputStream();  // 建立       
             buff = new BufferedOutputStream(outSTr);       
             write.append(result.replaceAll(",", enter));       
             buff.write(write.toString().getBytes("UTF-8"));       
             buff.flush();       
             buff.close();       
        } catch (Exception e) {  
        	System.out.println("导出串号出错!");
            e.printStackTrace();       
        } finally {       
            try {       
                buff.close();       
                outSTr.close();       
            } catch (Exception e) { 
            	System.out.println("导出串号出错!");
                e.printStackTrace();       
           }       
       }    
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

eadela

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值