总算是摸索出来了。趁热打铁,记录下来。
有这么一个表格页面。想要将通过筛选条件搜索出来的列表数据全部下载到本地,生成excel文件。如下图:
image.png
以上就是想要的效果。那么如何实现呢?
第一步:导入依赖(在pom.xml)
<!--解析Excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
第二步:新建一个excel控制器(ExcelController)
package com.lencity.securitymanagementplatform.controller;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
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.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import com.lencity.securitymanagementplatform.data.entity.User;
import com.lencity.securitymanagementplatform.data.service.UserService;
@RestController
@RequestMapping(value = "/excel")
public class ExcelController {
@Autowired
private UserService userService;
@PostMapping(value = "/getUser")
@ResponseBody
public String getUser(User formUser, HttpServletResponse response) throws Exception {
Map<String, String> condition = new HashMap<>();
String name = formUser.getName();
String departmentCode = formUser.getDepartmentCode();
if (name != "") {
condition.put("name", name);
}
if (departmentCode != "") {
condition.put("departmentCode", departmentCode);
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("统计表");// 创建一个excel表单
createTitle(workbook, sheet);
List<User> users = userService.getUsers(condition);
// 设置日期格式
HSSFCellStyle style = workbook.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
// 新增数据行,并且设置单元格数据
int rowNum = 1;
for (User user : users) {
HSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getMobile());
row.createCell(2).setCellValue(user.getPosition());
HSSFCell cell = row.createCell(3);
cell.setCellValue(user.getDepartmentCode());
cell.setCellStyle(style);
rowNum++;
}
String fileName = "导出excel.xls";
// 生成excel文件
buildExcelFile(fileName, workbook);
// 浏览器下载excel
buildExcelDocument(fileName, workbook, response);
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 1);
return jsonObject.toString();
}
// 创建表头
private void createTitle(HSSFWorkbook workbook, HSSFSheet sheet) {
HSSFRow row = sheet.createRow(0);
// 设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
sheet.setColumnWidth(1, 12 * 256);
sheet.setColumnWidth(3, 17 * 256);
// 设置为居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setFont(font);
HSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("手机号码");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("职位");
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue("部门");
cell.setCellStyle(style);
}
// 生成excel文件
protected void buildExcelFile(String filename, HSSFWorkbook workbook) throws Exception {
FileOutputStream fos = new FileOutputStream(filename);
workbook.write(fos);
fos.flush();
fos.close();
}
// 浏览器下载excel
protected void buildExcelDocument(String filename, HSSFWorkbook workbook, HttpServletResponse response)
throws Exception {
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
}
第三步:页面添加一个导出按钮。(不多说,so easy~)绑定一个点击事件,class的样式自然是可以和我不一样的。
<button type="button" class="btn btn-primary waves-effect" onclick="exportExcel()">
<i class="material-icons">add</i> <span>导出表格</span>
</button>
效果:
导出按钮
第四步:js部分,也是非常关键的一步!(在按钮对应的js文件中写点击事件)
在这一步呢,有一个注意点,一般来说我们要传数据回后台,且点击导出的时候又不希望页面刷新,当然会选择ajax异步传输啦。恩,我刚开始也是这么想的。于是用了ajax将搜索框的两个条件带入后台,表格确实能正常生成,关键是,浏览器不弹出下载保存的选择路径框(如下图)
选择路径框.png 啊,所以,我到处查原因,看到有好多人说要 image.png
加上这两句,那么没错啊,我加着呢,为啥还是不弹选择框呢,找了半天,终于有高手道出了真相!ajax是不能用来下载的。具体什么原因呢,我搜了一下,好像很深奥的样子,,看不懂,管他啥原因呢,不能下载那就换呗
为啥不能用ajax下载.png
于是我又开始疯狂搜索如何带多个参数进后台。重点来了!隐藏form表单post提交!隐藏form表单post提交!隐藏form表单post提交!恩,说三遍突出重点。那么如何操作呢?
1.在html页面,也就是你的导出按钮所在页面,添加一个form表单(在body标签里面的随意一个鸡旮沓角落放入两句话即可)
image.png
2.js
function exportExcel() {
var name = $("#name").val();
var departmentCode = $("#departmentCode").find("option:selected").val();
var form = $("<form>");
$('body').append(form);
form.attr('style','display:none');
form.attr('target','');
form.attr('method','post');
form.attr('action',contextPath+'/excel/getUser');//下载文件的请求路径
//对应查询条件的开始时间
var input1 = $('<input>');
input1.attr('type','hidden');
input1.attr('name',"name");
input1.attr('value',name);
form.append(input1);
//对应查询条件的结束时间
var input2 = $('<input>');
input2.attr('type','hidden');
input2.attr('name','departmentCode');
input2.attr('value',departmentCode);
form.append(input2);
form.submit();
}
以上:over~
网友评论