后台生成Excel时前端获取下载

Controller控制器:

package com.example.test.controller;

import com.example.test.common.HttpRequest;
import com.example.test.utils.ExcelUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List; @Controller
@RequestMapping(value = "/report")
public class TestController { public HttpRequest hr = new HttpRequest(); /**
* 导出Excel
*/
@RequestMapping(value = "/excel", produces = "application/json; charset=utf-8")
@ResponseBody
public void findExcel(HttpServletRequest request,HttpServletResponse response) {
String startTime = request.getParameter("startTime");
startTime = startTime+" 00:00:00";
String endTime = request.getParameter("endTime");
endTime = endTime+" 00:00:00";
String param = "startTime="+startTime+"&endTime="+endTime;
String baseURL = "http://localhost:8080";
String res = hr.sendPost(baseURL+"/getFinancingStat", param); System.out.println(res); List<JSONObject> list = JSONArray.fromObject(res); //excel标题
String[] title = {"业务员姓名","单量","业务员电话","业务员id"};
//excel文件名
String fileName = "业务员数据"+startTime+"至"+endTime+".xls";
//sheet名
String sheetName = "业务员数据";
String[][] content=new String[list.size()][title.length];
for (int i = 0; i < list.size(); i++) {
content[i] = new String[title.length];
JSONObject obj=list.get(i);
content[i][0] = obj.get("业务员姓名").toString();
content[i][1] = obj.get("单量").toString();
content[i][2] = obj.get("业务员电话").toString();
content[i][3] = obj.get("业务员id").toString();
} //创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null); //响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
} //发送响应流方法
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(),"ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

ExcelUtil生成Excel的样式:

package com.example.test.utils;

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 ExcelUtil { /**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){ // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
} // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName); // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0); // 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式 //声明列对象
HSSFCell cell = null; //创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
} //创建内容
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 1);
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
}

前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="../js/jquery.js"></script>
</head>
<body>
开始时间:<input class="form-control" type="date" id="startTime" /><br/><br/>
结束时间:<input class="form-control" type="date" id="endTime" /><br/><br/>
<button id="js-export" type="button" class="btn btn-primary">导出Excel</button>
</body>
<script>
$('#js-export').click(function(){
var startTime = document.getElementById("startTime").value;
var endTime = document.getElementById("endTime").value;
window.location.href="/report/excel?startTime="+startTime+"&endTime="+endTime+"";
});
</script>
</html>

maven中的配置:

    <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-examples -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-excelant -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>3.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>

后台生成excel前端下载的更多相关文章

  1. phpexcel生成excel并下载

    Loader::import('PHPExcel.Classes.PHPExcel'); // tp5中只需将phpexcel文件放入extend文件夹中,即可采用该方法引入,需要先 use thin ...

  2. 后台生成EXCEL文档,自定义列

    后台生成EXCEL文档,自定义列 //response输出流处理 //设置编码.类型.文件名 getResponse().reset(); getResponse().setCharacterEnco ...

  3. 使用node.js生成excel报表下载(excel-export express篇)

    引言:日常工作中已经有许多应用功能块使用了nodejs作为web服务器,而生成报表下载也是我们在传统应用. java中提供了2套类库实现(jxl 和POI),.NET 作为微软的亲儿子更加不用说,各种 ...

  4. java动态生成excel打包下载

    @SuppressWarnings("unchecked") public String batchExport() throws DBException{ @SuppressWa ...

  5. Asp.net MVC 简单实现生成Excel并下载

    由于项目上的需求,需要导出指定条件的Excel文件.经过一翻折腾终于实现了. 现在把代码贴出来分享 (直接把我们项目里面的一部份辅助类的代码分享一下) 我们项目使用的是Asp.Net MVC4.0模式 ...

  6. php ajax生成excel并下载

    目标:使用php,通过ajax请求的方式生成一个excel,然后下载. 思路:大致思路是发送一个ajax请求到后台,后台php处理后生成一个excel文件,然后把生成的文件放到一个临时目录,然后把文件 ...

  7. ASP.NET网页生成EXCEL并下载(利用DataGrid或GridView等)

    前几天要在后台查询数据库内容(用entity framework),将查询出来的信息(List或DataTable形式)转成EXCEL供用户下载.经过谷歌.百度搜索,终于搜出了一些代码.似乎可用了,结 ...

  8. NPOI生成excel并下载

    NPOI文件下载地址:http://npoi.codeplex.com/ 将文件直接引用至项目中即可,,,,, 虽然网上资料很多,但有可能并找不到自己想要的功能,今天闲的没事,所以就稍微整理了一个简单 ...

  9. Echarts 数据视图 生成Excel的方法

    一.生成Excel,两大方向:1后台生成Excel 查询数据库,使用NOPI生成Excel.2前台js生成Excel三种方式1)jquery.table2excel.js --采用,优势:兼容IE和C ...

随机推荐

  1. owin Claims-based认证登录实现

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext c ...

  2. python相关知识/技巧文摘

    python文件和目录操作 python连接mysql数据库 Python字符编码详解 unicode相关介绍

  3. django项目设计

    我们以前是只建立一个项目只建立一个app,如果我们要建立多个app的时候 并且这个app要写很多额视图的函数views内函数,要是建立很多种的时候就会造成很冗杂,不美观  我们未来增强解耦性,就把那个 ...

  4. 超简易复制Model对象(为后续备忘录设计模式博文做铺垫)

    超简易复制Model对象(为后续备忘录设计模式博文做铺垫) 复制整个Model需要实现NSCopy协议,可以想象是非常麻烦的一件事情,今天我跟大家分享一个不需要你做任何操作的复制Model对象的方法, ...

  5. Windows与Linux 互相访问,挂载过程

    开始使用Linux时浏览器无法访问,多次尝试以失败告终,果断放弃自我动手, 找了大神帮助,弄了半天终于可以访问.但是之前在Windows下的文件也不能放弃,从大神那里那里文档,然后进行尝试 1.在Wi ...

  6. [原创]获取JS数组最大值、最小值

    核心关键 JS有Array数组对象,使用prototype内置属性扩展,增加Array数组max().min()方法 具体代码 //最小值 Array.prototype.min = function ...

  7. 《C++ Primer Plus》读书笔记之八—对象和类

    第十章 对象和类   1.面向对象编程(OOP)的特性:抽象.封装和数据隐藏.多态.继承.代码的重用性. 2.指定基本类型完成了3项工作:①决定数据对象需要的内存数量.②决定如何解释内存中的位(lon ...

  8. Ardunio控制RGB的LED灯显示彩虹渐变色.

    由于我使用的是共阴极的RGB LED,如果你的是共阳极的,接线的时候要注意一下. 其他没什么不同 //定义RGB色彩的输出I/O ; ; ; //标记颜色变化的方式,增加值还是减小值 bool red ...

  9. 第二次作业:找Bug

    引子 我真的想了一个小时,上哪里去找bug.我昨天还留意到一个bug,今天就不见了.灵光不断,我想起来了.我就要找大公司的产品的bug... 第一部分 调研, 评测 体验. <腾讯桌球>是 ...

  10. 【笔记】JS脚本为什么要放在body最后面以及async和defer的异同点

    1.没有defer或async 浏览器遇到脚本的时候会暂停渲染并立即加载执行脚本(外部脚本),"立即"指的是在渲染该 script 标签之下的文档元素之前,也就是说不等待后续载入的 ...