java实现浏览器下载excel文件

本文介绍了一种在浏览器中导出数据至Excel文件的方法。利用Java API POI处理Excel文件,从前端获取筛选条件,服务端生成Excel并返回给前端进行下载。
之前有写过一个简单版的excel导出(简单,就是在本地导出),今天要说的是从浏览器将数据导出为excel文件,其实也可以看做是在浏览器下载这个excel文件
在实际工作生活中,常常会有这种场景。我们需要将页面上的表格导出到本地excel文件中,从表面上看是从网页上直接导出的,其实它是在服务端运行的,首先获取前端的筛选条件,根据条件调用查询方法,查到数据之后,创建工作薄,工作表,行,列等(这里需要引入一个POI<Apache针对微软的文档发明的一种javaAPI>的jar包),并且将数据放入表中,然后将excel写入输出流中,最后将输出流写进HttpServletResponse输出流中,在前端通过触发这个接口,就可以实现在浏览器下载该excel文件
下面通过一个实例来感受一下:(主要学思路......)
/**
 * 导出所有学生列表
 * @param request
 * @return
 */
@ResponseBody
@RequestMapping(value="/exportStudent",method=RequestMethod.POST)
//注意,这里StudentRequest和StudentResponse都是自己封装的实体类
//StudentResponse是用来返回数据的,StudentRequest是用来接收参数(可以看做是查询条件)
public StudentResponse exportStudent(StudentRequest request,HttpServletResponse response) {
//创建工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//创建工作表
HSSFSheet sheet = wb.createSheet();
//创建样式和字体
HSSFCellStyle curStyle = wb.createCellStyle();
HSSFFont curFont = wb.createFont();
//创建行列
HSSFRow nRow = sheet.createRow(0);
HSSFCell nCell = nRow.createCell(0);
//设置列的样式(具体实现在后面......)
nCell.setCellStyle(this.mainTitleStyle(curStyle, curFont));
//控制行号列号
int rowNo = 0;
int colNo = 0;
//列标题
String[] title;
title = new String[]{ "学号","年龄","性别","班级"};
//设置标题到第一行的列中
nRow = sheet.createRow(rowNo++);
for(int i = 0;i<title.length;i++) {
nCell = nRow.createCell(i);
nCell.setCellValue(title[i]);
nCell.setCellStyle(this.textStyle( curStyle, curFont));
}
//创建样式和字体(为什么又new,因为下面是正文部分了)
curStyle = wb.createCellStyle();
curFont = wb.createFont();
StudentResponse response = new StudentResponse();
try {
//通过调用逻辑层方法查询出数据
response  = StudentBiz.selectAllStudent(request);
List<StudentDto> studentList = response  .getStudentList();
//遍历并且创建行列
for (StudentDto dto : studentList ) {
colNo = 0;//控制列号
//每遍历一次创建一行
nRow = sheet.createRow(rowNo++);
//学号(先查询出,再将值设置到列中)
nCell = nRow.createCell(colNo++);
nCell.setCellValue(dto.getNum());
nCell.setCellStyle(this.textStyle( curStyle, curFont));
//年龄
nCell = nRow.createCell(colNo++);
nCell.setCellValue(dto.getAge);
nCell.setCellStyle(this.textStyle( curStyle, curFont));
//性别
nCell = nRow.createCell(colNo++);
nCell.setCellValue(dto.getSex);
nCell.setCellStyle(this.textStyle(curStyle, curFont));
//班级
nCell = nRow.createCell(colNo++);
nCell.setCellValue(dto.getClass);
nCell.setCellStyle(this.textStyle( curStyle, curFont));
}
//到这里,excel就已经生成了,然后就需要通过流来写出去
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//将excel写入流
wb.write(byteArrayOutputStream);
//设置文件标题			
String dateTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmm");
String outFile = "学生列表-"+dateTime + ".xls";
//设置返回的文件类型
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//对文件编码
outFile = response.encodeURL(new String(outFile.getBytes("gb2312"), "iso8859-1"));
//使用Servlet实现文件下载的时候,避免浏览器自动打开文件
response.addHeader("Content-Disposition", "attachment;filename=" + outFile);
//设置文件大小
response.setContentLength(byteArrayOutputStream.size());
//创建Cookie并添加到response中
Cookie cookie = new Cookie("fileDownload", "true");
cookie.setPath("/");
response.addCookie(cookie);
//将流写进response输出流中
ServletOutputStream outputstream = response.getOutputStream();
byteArrayOutputStream.writeTo(outputstream);

byteArrayOutputStream.close();
outputstream.flush();	
} catch (Exception e) {
parkVehicleResponse.setMsg("导出列表失败");
return parkVehicleResponse;
}
return null;
}
******以下两个方法是设置样式的方法,通常表格中标题和正文样式都不一样的,所以不同地方选择不同方法来设置样式
/**
 *  表格标题样式
 * @param curStyle
 * @param curFont
 * @return
 */
private HSSFCellStyle mainTitleStyle( HSSFCellStyle curStyle, HSSFFont curFont) {
curStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);	//水平居中
curStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
curFont.setFontName("宋体");	//字体
curFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 加粗
curFont.setFontHeightInPoints((short) 16);//字体大小
curStyle.setFont(curFont); // 绑定关系
return curStyle;
}	
/**
 * 表格内容样式
 * @param curStyle
 * @param curFont
 * @return
 */
private HSSFCellStyle textStyle(HSSFCellStyle curStyle, HSSFFont curFont) {
curStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);//左对齐
curStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
curStyle.setWrapText(true); // 自动换行
curStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 实线
curStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 实线
curStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 实线
curStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 实线
curFont.setFontName("Times New Roman");//字体
curFont.setFontHeightInPoints((short) 10);//字体大小
curStyle.setFont(curFont); // 绑定关系
return curStyle;
}
在前端只要通过某一个事件(比如:点击)来触发这个URL("/exportStudent")就可以实现在浏览器将该文件导出来
### 使用 Java 实现浏览器导出 Excel 文件并触发下载Java Web 应用中实现导出 Excel 文件并通过浏览器触发下载是一个常见的需求,尤其是在数据报表和文件导出场景中。通常可以通过 Apache POI 或 EasyExcel 等库来操作 Excel 文件,并通过设置响应头来触发浏览器文件下载行为。 #### 1. **使用 Apache POI 实现导出并下载 Excel 文件** Apache POI 是一个强大的 Java 库,用于处理 Microsoft Office 文档,包括 Excel 文件(`.xls` 和 `.xlsx`)。以下是一个简单的示例,展示如何在 Servlet 中生成 Excel 文件并通过浏览器下载: ```java import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; @WebServlet("/export-excel") public class ExcelExportServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Workbook workbook = new XSSFWorkbook(); var sheet = workbook.createSheet("User Data"); // 创建表头 var headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("ID"); headerRow.createCell(1).setCellValue("Name"); headerRow.createCell(2).setCellValue("Email"); // 添加数据行 List<Map<String, Object>> dataList = new ArrayList<>(); Map<String, Object> user1 = new HashMap<>(); user1.put("ID", 1); user1.put("Name", "Alice"); user1.put("Email", "alice@example.com"); dataList.add(user1); int rowNum = 1; for (Map<String, Object> data : dataList) { var row = sheet.createRow(rowNum++); row.createCell(0).setCellValue((Integer) data.get("ID")); row.createCell(1).setCellValue((String) data.get("Name")); row.createCell(2).setCellValue((String) data.get("Email")); } // 设置响应头以触发浏览器下载 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=users.xlsx"); workbook.write(response.getOutputStream()); workbook.close(); } } ``` 此代码创建了一个包含用户信息的 Excel 文件,并将其写入 `HttpServletResponse` 的输出流中。浏览器会根据 `Content-Disposition` 响应头自动触发下载行为[^1]。 --- #### 2. **使用 EasyExcel 实现导出并下载 Excel 文件** EasyExcel 是阿里巴巴开源的一个轻量级 Excel 操作库,特别适合处理大数据量的 Excel 导出任务,且内存占用较低。以下是使用 EasyExcelJava Web 应用中导出 Excel 并触发下载的示例: 首先定义一个实体类: ```java public class User { private int id; private String name; private String email; // Getters and Setters } ``` 然后在 Servlet 中使用 EasyExcel 进行导出: ```java import com.alibaba.easyexcel.EasyExcel; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet("/easy-export") public class EasyExcelExportServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { // 设置响应头 response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment; filename=users_easy.xlsx"); // 准备数据 List<User> userList = new ArrayList<>(); userList.add(new User(1, "Alice", "alice@example.com")); userList.add(new User(2, "Bob", "bob@example.com")); // 使用 EasyExcel 写入数据到输出流 EasyExcel.write(response.getOutputStream(), User.class) .sheet("User Data") .doWrite(userList); } } ``` 该示例展示了如何使用 EasyExcel 快速将数据导出为 Excel 文件,并通过浏览器触发下载。由于 EasyExcel 对大数据量的支持较好,因此在处理大规模数据时更具优势[^2]。 --- #### 3. **自定义工具类实现灵活导出** 如果你希望构建一个通用的 Excel 导出工具类,可以结合 Apache POI 或 EasyExcel 提供更灵活的功能,例如支持模板、样式、图片插入等高级功能。以下是一个简化版的工具类示例: ```java public class ExcelExporter { public static void exportToExcel(HttpServletResponse response, List<?> dataList, Class<?> clazz, String sheetName, String fileName) throws IOException { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx"); EasyExcel.write(response.getOutputStream(), clazz) .sheet(sheetName) .doWrite(dataList); } } ``` 该工具类可以被多个 Servlet 复用,只需传入不同的数据、类类型和文件名即可实现灵活导出[^3]。 --- ###
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值