java导出excel,txt

来源:互联网 发布:在线算法的特点 编辑:程序博客网 时间:2024/05/21 17:57

导出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游戏客服3window.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_KEYpublic static void exportExcel(HttpServletResponse response,String excelName,String[] excelHeader,Map<Integer, String[]> hashMap) {// 第一步,创建一个webbook,对应一个Excel文件HSSFWorkbook wb = new HSSFWorkbook();// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheetHSSFSheet sheet = wb.createSheet(excelName);// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制shortHSSFRow 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();                  }              }    }




原创粉丝点击