本案例使用SpringMVC
第一步
查询出所需信息
封装到list集合当中
like this
List<SysLog> logList = sysLogAspect.queryAllSysLog();
第二步 填写Excel
// 生成Excel文件
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
HSSFSheet sheet = hssfWorkbook.createSheet("日志数据");
// 表头 可根据需要自行添加
HSSFRow headRow = sheet.createRow(0);
headRow.createCell(0).setCellValue("行数");
headRow.createCell(1).setCellValue("用户编码");
// 表格数据 可根据需要自行添加
for (SysLog sysLog : logList) {
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(sysLog.getId());
dataRow.createCell(1).setCellValue(sysLog.getUserId());
}
// 下载导出
// 设置头信息
response.setContentType(
"application/vnd.ms-excel");
String filename = "日志数据.xls";
String agent = request.getHeader("user-agent");
filename = FileUtils.encodeDownloadFilename(filename, agent);
response.setHeader("Content-Disposition",
"attachment;filename=" + filename);
ServletOutputStream outputStream = response.getOutputStream();
hssfWorkbook.write(outputStream);
// 关闭
hssfWorkbook.close();
工具类代码
public class FileUtils {
/**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public static String encodeDownloadFilename(String filename, String agent)
throws IOException {
if (agent.contains("Firefox")) { // 火狐浏览器
filename = "=?UTF-8?B?"
+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
+ "?=";
filename = filename.replaceAll("\r\n", "");
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+"," ");
}
return filename;
}
}