SpringMvc将web端数据导出Excel(和遇到的坑)

之前导出都是直接去controller层 找对应方法导出的
这次用的相同的方法 却不行 找了一晚上 才发现 我这次用的是ajax 请求该方法 方法也进去了io流读写操作也执行了就是 Excel文件下载不下来。
改之前的ajax:
在这里插入图片描述
改之后的直接访问controller层方法:
我传过去的idlist是我页面要导出的 数据的id
在这里插入图片描述

 location="<%=basePath%>device/checkOutxls?idList="+idList.toString();

以上就是我遇到的坑 将ajax的请求方式 改成 location直接访问方法即可。
一下是所有主要功能代码:

前端js:获取选中的id的信息

var checkedNum = $("input[name='checkDeivce']:checked").length;
    if (checkedNum == 0) {
    	zeroModal.alert("请至少选择一个!");  
    	return false
    }
    //获取选择的id序号
    var idList = new Array();
    $("input[name='checkDeivce']:checked").each(function() {
    	idList.push($(this).parent().parent().find("td").eq(0).text());//id 的序号 集合
    });
    	location="<%=basePath%>device/checkOutxls?idList="+idList.toString(); 

location过去的controller层代码

@RequestMapping("/checkOutxls") 
		public void checkOutxls( 
				HttpServletRequest request, HttpServletResponse response) {
	    	String idList = request.getParameter("idList"); 
	    	// 1、文件叫啥名称
			DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			String date=fmt.format(LocalDateTime.now());
			String fileName = date+"example"+".xlsx";//最终命名  
			// 2、存放的路径是啥
			ServletContext application = request.getServletContext();
			String path = application.getRealPath("excel");
			path = "C:/Users/Administrator/Desktop";
			path += File.separator + fileName;//最终路径
			/*String id[] = {};
			try {
				id = arr.split(",");
			} catch (Exception e) {
				e.printStackTrace();
			}*/
			String[] strs = idList.split(",");//将string的id字符串以“,”分成数组
			List<Device> list = new ArrayList<Device>();//需要导出的数据集合
			for (String str : strs) {
	        	int id=Integer.valueOf(str);//string 转 int
				Device device=deviceService.selDeviceById(id);//在根据id获取对象
				list.add(device);//将对象一一存入list集合
			}
			//System.out.println("需要打印的数据: " + list); 
			// 3、执行上传excel
			ExcelUtil.creatExcel(list, path);   
			// 4、执行下载
			FileUpAndDownload.download(request, response, fileName, path); 
			
		}

ExcelUtil代码有两个方法都可以用 我用的第一个

//读写excel的工具类
@Component("excelUtil")
public class ExcelUtil {

	public static Object createExcel;

	// 把list中的user对象读出来,写到excel中
	public static int creatExcel(List<Device> list, String path) {
		// 1、指定目标文件
		File target = new File(path);
		OutputStream out = null;
		XSSFWorkbook book = null;
		try {
			out = new FileOutputStream(target);
			// 2、创建工作簿
			book = new XSSFWorkbook();
			// 3、创建工作簿中的页,指定页的名称
			XSSFSheet sheet = book.createSheet("device");
			// 4、创建行
			int rowNum = 0;
			XSSFRow row = sheet.createRow(rowNum++); 
			// 5、创第一行的单元格并设置值
			int coulumNum = 0;
			row.createCell(coulumNum++).setCellValue("序号");
			row.createCell(coulumNum++).setCellValue("手机品牌");
			row.createCell(coulumNum++).setCellValue("手机型号");
			row.createCell(coulumNum++).setCellValue("唯一标识");
			row.createCell(coulumNum++).setCellValue("采集时间");
			// 6、循环输出user对象
			for (int i = 0; i < list.size(); i++) {
				Device device = list.get(i);
				coulumNum = 0;
				row = sheet.createRow(rowNum++);
				row.createCell(coulumNum++).setCellValue(device.getId());
				row.createCell(coulumNum++).setCellValue(device.getVendor());
				row.createCell(coulumNum++).setCellValue(device.getModel());
				row.createCell(coulumNum++).setCellValue(device.getImei());
				row.createCell(coulumNum++).setCellValue(device.getDateTime());
				//System.out.println(device); 

			}
			// 7、保存文件
			book.write(out);
			System.out.println("表创建成功!");
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 8、关闭流
			if (book != null) {
				try {
					book.close();
				} catch (Exception e) {
				}
			}
		}
		return 0;
	}

	// 通用的创建excel表的方法
	public static <T> int createExcels(Class<T> clazz, List<T> list, String path) {
		OutputStream out = null;
		XSSFWorkbook book = null;
		try {
			// 1、指定目标文件
			File target = new File(path);
			out = new FileOutputStream(target);
			// 2、创建工作簿
			book = new XSSFWorkbook(); 
			// 3、创建工作簿中的页,指定页的名称
			XSSFSheet sheet = book.createSheet(clazz.getSimpleName() + "device");
			// 4、创建第1行
			int rowNum = 0;
			XSSFRow row = sheet.createRow(rowNum++);
			Field[] field = clazz.getDeclaredFields();
			// 从1开始把序列号属性去除
			for (int i = 1; i < field.length; i++) {
				String name = field[i].getName();
				row.createCell(i).setCellValue(name);
			}
			// 5、遍历集合,拼接下一行
			for (int i = 0; i < list.size(); i++) {
				// 创建下一行
				row = sheet.createRow(rowNum++);
				// 遍历所有的属性
				for (int j = 1; j < field.length; j++) {
					// 获得属性的名称
					String name = field[j].getName();
					// 把属性名首字母转大写
					name = Commons.upperCaseFirstChar(name);
					// 获得集合的元素对象
					T t = list.get(i);
					// 执行当前类的方法get方法 
					Method mt = clazz.getDeclaredMethod("get" + name);
					// 获得当前getter方法的返回值类型
					Class<?> cl = mt.getReturnType();
					// 判断返回值类型,对单元格进行设置值
					String type = cl.getSimpleName();
					//System.out.println(type);
					if (type.equals("String")) {
						if (mt.invoke(t) == null) {
							row.createCell(j).setCellValue("");
						} else {
							String obj = (String) (mt.invoke(t));
							row.createCell(j).setCellValue(obj);
						}
					} else if (type.equals("Long")) {
						if (mt.invoke(t) == null) {
							row.createCell(j).setCellValue("");
						} else {
							Long obj = (Long) (mt.invoke(t));
							row.createCell(j).setCellValue(obj);
						}
					} else if (type.equals("Integer")) {
						if (mt.invoke(t) == null) {
							row.createCell(j).setCellValue("");
						} else {
							Integer obj = (Integer) (mt.invoke(t));
							row.createCell(j).setCellValue(obj);
						}
					} else if (type.equals("Date")) {
						if (mt.invoke(t) == null) {
							row.createCell(j).setCellValue("");
						} else {
							Date obj = (Date) (mt.invoke(t));
							row.createCell(j).setCellValue(obj);
						}
					} else {
						// 除此之外全部设置空
						row.createCell(j).setCellValue("");
					}
				}
			}
			// 6、保存文件
			book.write(out);
			System.out.println("创建表成功");
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 7、关闭流
			if (book != null) {
				try {
					book.close();
				} catch (Exception e) {
				}
			}
		}
		return 0;
	}


}

FileUpAndDownload工具类代码

@Component("fileUpAndDownload")
public final class FileUpAndDownload { 
	// 下载方法
	public static Boolean download(HttpServletRequest request, HttpServletResponse response, String fileName, String path) {
		// 1、构建流的对象
		InputStream is = null;
		OutputStream out = null;
		// 2、设置响应头
		try {
			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 3、设置响应的数据类型
		response.setContentType("multipart/form-data");
		// 4、边读边写
		byte[] bt = new byte[1024];
		int len;
		try {
			is = new FileInputStream(path);
			out = response.getOutputStream();
			while ((len = is.read(bt)) != -1) {
				out.write(bt, 0, len);
			}
			out.flush();
			System.out.println("表下载成功!");
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 5、关闭资源
			if (out != null) {
				try {
					out.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			// 6、删除源文件
			new File(path).delete();
		}
		return false;
	}
}

以上就是全部代码 效果如下:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值