ssm导出Excel表格

最近在做一个导出Excel表格到客户端的功能,想了一下,好像不能直接导出客户端呀,然后就换一个形式下载到客户端。
写不好的地方,请大神指点指点,thank

代码如下:

1.需要注入POI依赖

<!-- 省略ssm依赖包 -->
		...
<!-- 导出EXCEL表格 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.6</version>
</dependency>

2.定义一个controller处理类

/**
 * @author zhuangchongyi
 * @Description: 处理Excel标的的请求类
 * @date 2019年9月11日 下午7:58:13
 * @version V1.0
 */
@Controller
@RequestMapping("/export/")
public class ExportExcelController {
	@Autowired
	private ArchiveService archiveService;
 
    @RequestMapping("studentArchiveDownload")
	public void exportStudentArchiveDownloadExcel(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		// 查询学生档案信息
		List<ArchiveStudent> stuArchiveList = archiveService.findArchiveStudentByUserid("1008611");
		int length = stuArchiveList.size(); // 数据行数
		if (stuArchiveList == null || length == 0) {
			response.getWriter().write("导出失败,暂无数据可导出");
			response.setHeader("refresh", "2;url=http://localhost/MySystem/demo/download.html");
		}

		// 导出存放路径
		String exportPath = request.getSession().getServletContext().getRealPath("excel");
		System.out.println(exportPath);
		File file = new File(exportPath);
		if (file.exists()) {
			file.mkdirs(); // 创建文件夹
		}
		// 格式化日期
		SimpleDateFormat sdf = new SimpleDateFormat("YYYY年MM月DD日");

		String sheetName = "学生视力档案"; // 底部标题
		String fileName = sheetName + new Date().getTime(); // 文件名称
		String[] title = { "测试关联id", "创建人", "姓名", "身份证", "性别", "年龄/岁", "身高/cm", "学校", "年级", "班级", "地区", "创建时间" }; // 标题字段
		String[][] values = new String[length][];	//行列值
		for (int i = 0; i < length; i++) {
			values[i] = new String[title.length];	//行值
			values[i][0] = stuArchiveList.get(i).getSid();
			values[i][1] = stuArchiveList.get(i).getUserid();
			values[i][2] = stuArchiveList.get(i).getName();
			values[i][3] = stuArchiveList.get(i).getUuid();
			values[i][4] = stuArchiveList.get(i).getGender();
			values[i][5] = stuArchiveList.get(i).getAge();
			values[i][6] = stuArchiveList.get(i).getHeight();
			values[i][7] = stuArchiveList.get(i).getSchool();
			values[i][8] = stuArchiveList.get(i).getSgarde();
			values[i][9] = stuArchiveList.get(i).getSclass();
			values[i][10] = stuArchiveList.get(i).getAddress();
			values[i][11] = sdf.format(stuArchiveList.get(i).getCreatetime());
		}
		// 获取HSSFWorkbook 对象
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
		
		//结合其他的表输出

		String fileName2 = fileName + ".xls";
		boolean flag = ExcelUtil.createExcel(exportPath, fileName2, wb);//导出excel文件
		System.out.println(flag);
		if (flag) {
			// 创建成功则进行压缩下载
			ZipUtil.setZipDownload(fileName,request,response);
			// 压缩
			String[] fileNameArr = {fileName2};
			ZipUtil.downloadZip(exportPath, fileNameArr, response);//这里已经作出了相应,所以不能再重定向或转发,也不能返回信息,否则会报错
			
			System.out.println("export ok");
			return ;
		} else {
			System.out.println("export fail");
			return ;
		}

	}
 }

3.定义一个处理Excel表格的工具类

/**
 * @author zhuangchongyi  
 * @Description: Excel表格导出工具类
 * @date 2019年9月12日 上午11:00:19 
 * @version V1.0
 */
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) {
		// 1.创建一个HSSWorkbook对象,对应一个Excel文件
		if (wb == null)
			wb = new HSSFWorkbook();
		// 2.在workbook当中添加一个sheet,对应Excel中的sheet
		HSSFSheet sheet = wb.createSheet(sheetName);
		// 3.在sheet表头添加第0行,老版本的poi对Excel的行数有限制
		HSSFRow row = sheet.createRow(0);
		// 4.创建单元格,并设置表头,设置表头居中
		HSSFCellStyle style = wb.createCellStyle();
		// 4.1创建一个居中表格
		style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		// 4.2声明列对象
		HSSFCell cell = null;
		// 4.3创建标题
		for (int i = 0; i < title.length; i++) {
			cell = row.createCell(i);
			cell.setCellValue(title[i]);
			cell.setCellStyle(style);
		}
		// 4.4创建内容
		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;
	}

	/**
	 * 生成excel表格
	 * @param exportPath 存放路径
	 * @param fileName 生成文件名
	 * @param wb HSSFWorkbook对象
	 * @return 返回生成是否成功
	 */
	public static boolean createExcel(String exportPath, String fileName, HSSFWorkbook wb) {
		boolean flag = false;
		// 解析流
		FileOutputStream fos = null;
		try {
			File dirFile = new File(exportPath);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			fos = new FileOutputStream(exportPath + File.separator + fileName);
			wb.write(fos);
			fos.close();
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			return flag;
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
				return flag;
			}
		}
		return flag;
	}

}

4.定义一个压缩成.zip的工具类

/**
 * @author zhuangchongyi
 * @Description: 打包成zip工具类
 * @date 2019年9月12日 上午10:16:41
 * @version V1.0
 */
public class ZipUtil {
	/**
	 * 执行压缩文件
	 * 
	 * @param pathArr
	 *            文件路径数组
	 * @param nameArr
	 *            文件名数组
	 * @param response
	 *            响应对象
	 */
	public static void downloadZip(String path, String[] nameArr, HttpServletResponse response) {
		ZipOutputStream zipos = null;
		DataOutputStream dos = null;
		try {
			// 设置压缩流:直接写入response,实现边压缩边下载
			zipos = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
			zipos.setMethod(ZipOutputStream.DEFLATED);// 设置压缩方法

			// 循环将文件写入压缩流
			for (int i = 0; i < nameArr.length; i++) {
				File file = new File(path + File.separator + nameArr[i]);
				if (file.exists()) { // 判断文件是否存在
					// 添加ZipEntry,并将其写入文件流
					// 目的是为防止下载的文件时有重名导致下载失败
					zipos.putNextEntry(new ZipEntry(nameArr[i]));
					dos = new DataOutputStream(zipos);
					InputStream in = new FileInputStream(file);
					byte[] b = new byte[1024];
					int len = 0;
					while ((len = in.read(b)) != -1) {
						dos.write(b, 0, len);
					}
					in.close();
					zipos.closeEntry();
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (zipos != null)
					zipos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * 设置响应为下载格式化,定义下载文件名
	 * 
	 * @param fileName
	 *            文件名
	 * @param request
	 * @param response
	 */
	public static void setZipDownload(String fileName, HttpServletRequest request, HttpServletResponse response) {
		// 获取客户端浏览器版本号,协议
		String header = request.getHeader("USER-AGENT");
		try {
			// 针对IE或者IE内核的浏览器
			if (header.contains("MSIE") || header.contains("Trident")) {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else {
				// 非IE浏览器的处理
				fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 高速浏览器已下载的形式
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".zip");
	}
}

感谢观看

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

搬砖的小庄啊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值