首先,导包就不再赘述,具体看代码实现:
后台代码
//在内存中创建一个Excel文件
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个标签页
HSSFSheet sheet = workbook.createSheet("sheet1");
//创建标题行
HSSFRow headRow = sheet.createRow(0);
//创建标题行的内容
headRow.createCell(0).setCellValue("A");
headRow.createCell(1).setCellValue("B");
headRow.createCell(2).setCellValue("C");
headRow.createCell(3).setCellValue("D");
headRow.createCell(4).setCellValue("E");
//循环遍历填充数据
for(Person person: personList) {
//创建行
HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
dataRow.createCell(0).setCellValue(person.getId());
dataRow.createCell(1).setCellValue(person.getName());
dataRow.createCell(2).setCellValue(subarea.getAge());
dataRow.createCell(3).setCellValue(subarea.getGender());
dataRow.createCell(4).setCellValue(subarea.getAddress());
}
//使用输出流进行文件下载
String filename = "人员数据.xls";
//获取xls文件的文件类型
String contentType = ServletActionContext.getServletContext().getMimeType(filename);
//拿到输出流
ServletOutputStream out = ServletActionContext.getResponse().getOutputStream();
//设置文件类型
ServletActionContext.getResponse().setContentType(contentType);
//获取客户端浏览器类型
String agent = ServletActionContext.getRequest().getHeader("User-Agent");
//FileUtils是一个针对不同浏览器进行附件名编码的工具类(防止中文乱码)
filename = FileUtils.encodeDownloadFilename(filename, agent);
//设置头
ServletActionContext.getResponse().setHeader("content-disposition", "attachment;filename=" + filename);
workbook.write(out);
FileUtils是我在网上找的一个针对不同浏览器进行附件名编码的工具类,代码也贴在下方:
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;
}
}