1.导入依赖
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
2.编写ExcelUtil
package com.dev.dorimitory.util;
import org.apache.poi.hssf.usermodel.*;
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;
}
}
3.判断Checkbox是否选中
<label class="ftdms-checkbox checkbox-primary" style="width: 0em;">
<input onchange="return cbChange('${stu.s_id}')" type="checkbox" class="sigleCheckbox" name="s_id" value="${stu.s_id}"><span></span>
</label>
function cbChange(s_id) {
var s_id = [];
$("input[name='s_id']:checked").each(function (i) {
s_id[i] = $(this).val();
});
$.ajax({
data:{'s_id':s_id},
dataType:'text',
success: function(data){
alert(data);
},
type:'post',
url:'${pageContext.request.contextPath}/findStudentListById',
traditional:true
}
);
}
4.在Controller编写
@PostMapping(value = "findStudentListById")
public void findStudentListById(HttpServletRequest request,HttpSession session){
String[] s_ids = request.getParameterValues("s_id");
Integer[] ints = new Integer[s_ids.length];
for(int i=0;i<s_ids.length;i++){
ints[i] = Integer.parseInt(s_ids[i]);
}
List<Integer> list = new ArrayList<>(ints.length);
for(Integer s:ints) {
list.add(s);
}
List<Student> studentListById = studentService.findStudentListById(list);
session.setAttribute("studentListById",studentListById);
}
//excel文件名
public static String fileName = "学生信息表"+System.currentTimeMillis()+".xls";
//sheet名
public static String sheetName = "学生信息表";
//excel标题
public static String[] title = {"学号","姓名","性别","年龄","电话","班级编号","班级名","寝室编号"};
/**
* 导出报表
* @return
*/
@RequestMapping(value = "/export")
public void export(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws Exception {
//获取数据
List<Student> studentListById = (List<Student>) session.getAttribute("studentListById");
if (studentListById != null) {
String [][] content = new String[studentListById.size()][];
for (int i = 0; i < studentListById.size(); i++) {
content[i] = new String[title.length];
Student obj = studentListById.get(i);
content[i][0] = obj.getS_studentid();
content[i][1] = obj.getS_name();
content[i][2] = obj.getS_sex();
content[i][3] = obj.getS_age().toString();
content[i][4] = obj.getS_phone();
content[i][5] = obj.getS_classid();
content[i][6] = obj.getS_classname();
content[i][7] = obj.getS_dormitoryid().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();
}
} else{
//获取数据
List<Student> list = studentService.getAll();
String [][] content2 = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
content2[i] = new String[title.length];
Student obj = list.get(i);
content2[i][0] = obj.getS_studentid();
content2[i][1] = obj.getS_name();
content2[i][2] = obj.getS_sex();
content2[i][3] = obj.getS_age().toString();
content2[i][4] = obj.getS_phone();
content2[i][5] = obj.getS_classid();
content2[i][6] = obj.getS_classname();
content2[i][7] = obj.getS_dormitoryid().toString();
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content2, 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");
response.setHeader("Cache-Control", "no-store");
} catch (Exception ex) {
ex.printStackTrace();
}
}