主要的效果是
1.因为特殊要求需要,查询完之后再进行导出,也就是接口中除了text和response,其他都是条件字段。
2.点击导出,出现选择的相应字段也就是接口中接收的text。
3.选择字段只有点击确定,进行导出。
//这里给的是一个点击事件,点击按钮发送请求
<button type="button" class="btn btn-small btn-primary" data-dismiss="modal" onclick="outExcel()">确认</button>
//传递的参数来源不同
function outExcel() {
//此处是选中要导出的字段@1
var obj=[];
$(".sys_spec_text .active").each(
function () {
var text = $(this).text();
obj.push(text);
}
)
//此处是input框中的内容
var startTime= $("#startTime").val();
var endTime=$("#endTime").val();
//此处是下拉框选中的内容
var dProjectId= $('#projectId option:selected').val();
var dContract=$('#contractId option:selected').val();
//此处是span中选中的内容@2
if(condition=="" ||condition==null ){
var theMonth=null;
}else{
theMonth=condition;
}
var dType=$('#dType option:selected').val();
//请求后端接口,因为之前接口的原因,不方便将参数封装到数组中,所以都单个传过去了,这里要注意多个参数的拼接
location.href = "/dangerinformaticas/outExcel?text=" +obj+"&startTime="+startTime+"&endTime="+endTime+"&dProjectId="+dProjectId+"&dContract="+dContract+"&theMonth="+theMonth+"&dType="+dType;
}
在页面中的代码块
@1. 选中要勾选的字段
@2.span 中选中元素
`
var condition;
$(".time-btn .form-control").click(function () {
$(this).addClass("select-on").siblings().removeClass("select-on");
condition = $('.select-on').attr("name");
});
controller层
/*
导出excel
字段接受要进行要和实体类的类型一一对应
*/
@GetMapping("/outExcel")
public void exportToExcel(HttpServletResponse response,String text,String dUnitId,String startTime,String endTime,String dProjectId,String dContract,String theMonth,String dType) throws Exception {
//参数中HttpServletResponse response,是为了下载的位置不是固定的,统一存到服务器端的位置
//特殊情况的判断(本月、本季度、本年)
String theQuarter = null;
String theYear = null;
if(theMonth!=null ||theMonth!="" ){
if(theMonth=="0"){
theMonth="theMonth";
}else if(theMonth=="1"){
theMonth=null;
theQuarter="theQuarter";
}else{
theMonth=null;
theYear="theYear";
}
}
//根据特殊要求,查找到相对性的list
List<Dangerinformatica> dangerListAll=dangerinformaticaDao.getListAll(dUnitId,startTime,endTime,dProjectId,dContract,theMonth,theQuarter,theYear,dType);
//接收要导出的字段进行处理,字符串转到数组当中
List<String> listText=new ArrayList();
listText.addAll(Arrays.asList(text.split(",")));
//这个是要导出的所有字段放到一个map集合
HashMap<String, String> map = new HashMap();
//循环时相同的字段放到map1集合
HashMap<String, String> map1 = new HashMap();
map.put("projectName","项目");
map.put("contractName","合同段");
map.put("id","隐患编号");
map.put("dispictDanger","隐患描述");
map.put("dLecel","风险级别");
map.put("searchType","排查类型");
map.put("dType","安全/质量");
map.put("dIterm","隐患条目内容");
map.put("uploadName","提交人");
map.put("unitName","提交人单位");
map.put("createTime","提交时间");
//外循环map,内循环list,相同的字段存到map1
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> entry= it.next();
String value= entry.getValue();
for (String str:listText){
if(value.equals(str)){
map1.put(entry.getKey(),entry.getValue());
break;
}
}
}
//reponse:保存下载时放到一个地址;map1最终需要导出的字段;dangerList是查询到的所有的值
ExcelUtil.outExcel(response,map1,dangerListAll);
}
工具类的使用ExcelUtil
package com.boot.security.server.utils;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExcelUtil {
private String filePath;
private String sheetName;
private Workbook workBook;
private Sheet sheet;
private List<String> columnHeaderList;
private List<List<String>> listData;
private List<Map<String,String>> mapData;
private boolean flag;
public ExcelUtil(){
}
public ExcelUtil(String filePath, String sheetName) {
this.filePath = filePath;
this.sheetName = sheetName;
this.flag = false;
this.load();
}
/**
* 垂直水平居中风格
*表格导出样式限制
* @param wb
* @return
*/
private static CellStyle createVHCenterStyle(final Workbook wb) {
final CellStyle style = wb.createCellStyle(); // 样式对象
style.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直
style.setAlignment(HorizontalAlignment.CENTER);// 水平
style.setWrapText(true);// 指定当单元格内容显示不下时自动换行
return style;
}
/**
* 导出excel表格
* path文件将要保存的路径
* map是字段名为key 中文是value list是源数据
* @throws IOException
* @throws ParseException
*/
public static boolean outExcel( HttpServletResponse response, Map<String,String> map, List<?> list) throws IOException, ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 ");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
XSSFWorkbook workbook = new XSSFWorkbook();
OutputStream outputStream=response.getOutputStream();
if(list==null||list.size()==0 || map==null||map.size()==0 ) {
workbook.write(outputStream);
outputStream.close();
return true;
}
Class<? extends Object> c = list.get(0).getClass();
// 创建excel工作薄
// 创建一个工作表sheet
XSSFSheet sheet = workbook.createSheet();
String sheetName =sdf1.format(new Date());
response.setHeader("Content-Disposition", "attachment;filename="+sheetName+"隐患汇总表.xlsx");
response.setContentType("application/vnd.ms-excel");
// 创建行
for(int i =0;i<=list.size();i++) {
sheet.createRow(i);
for(int k=0;k<=map.size();k++) {
sheet.getRow(i).createCell(k);
}
}
//格式设置,存入wb
CellStyle vHCenterStyle = createVHCenterStyle(workbook);
Field[] f = c.getDeclaredFields();
int i=0;
for(Field fi:f) {
String str = fi.toString();
String sub = str.substring(str.lastIndexOf('.')+1);
Set<String> key = map.keySet();
for(String name:key) {
if(sub.equals(name)) {
sheet.getRow(0).getCell(i).setCellValue(map.get(name));
//这里是取出里list中所有的value
for(int j=1;j<=list.size();j++) {
Object o = list.get(j-1);
XSSFRow row = sheet.getRow(j);
Cell cell = row.getCell(i);
row.getCell(i).setCellStyle(vHCenterStyle);
Object value = getFieldValueByName(name,o);
//如果是value的类型是data进行格式化,否则导出Date类型的时间
if(value instanceof Date){
value = sdf.format((Date)value);
}
//name表示导出字段所对应的的实体类中的名称
if(name=="dType") {
if (value.equals("1")) {
//数据库存放的是1,2,判断进行赋值
value = "安全类";
} else {
value = "质量类";
}
}
if(name=="searchType") {
if (value.equals("1")) {
value = "日常排查";
} else if(value .equals("2")){
value = "定期排查";
}else{
value = "专项排查";
}
}
if(value!=null) {
cell.setCellValue(value.toString());
}
}
i++;
}
}
}
//最后流要记得关闭
workbook.write(outputStream);
outputStream.close();
return true;
}
private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter="";
if("eId".equals(fieldName) || "eName".equals(fieldName)) {
firstLetter = fieldName.substring(0, 1);
}else {
firstLetter = fieldName.substring(0, 1).toUpperCase();
}
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}