java如何生成excel返回给前端
前端的导出excel表格当数据大量时浏览器爆炸
常用的组件和样式
常用组件:
HSSFWorkbook excel的文档对象
HSSFSheet excel的表单
HSSFRow excel的行
HSSFCell excel的格子单元
HSSFFont excel字体
样式:
HSSFCellStyle cell样式
实现步骤
正确顺序应该是:
一、用HSSFWorkbook打开或者创建“Excel文件对象”
二、用HSSFWorkbook对象返回或者创建Sheet对象
三、用Sheet对象返回行对象,用行对象得到Cell对象
四、对Cell对象读写。
五、将生成的HSSFWorkbook放入HttpServletResponse中响应到前端页面
代码实现
- 资源的引入pom.xml中
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
- utils工具类主要生成excel文件
public class ExcelUtils {
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String []title, String [][]values, HSSFWorkbook wb){
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if(wb == null){
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
//声明列对象
HSSFCell cell = null;
//创建标题
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
//创建内容
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;
}
}
- controller层的编写
/**
* 导出报表
*
* @return
*/
@RequestMapping(value = "/export")
@ResponseBody
public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
//获取数据
List<PageData> list = userService.serviceList();
//excel标题
String[] title = {"用户ID", "用户名称", "用户密码", "用户手机","创建时间"};
//excel文件名
String fileName = "用户信息表" + System.currentTimeMillis() + ".xls";
//sheet名
String sheetName = "用户信息表";
String [][] content = new String[list.size()][5];
for (int i = 0; i < list.size(); i++) {
content[i] = new String[title.length];
PageData obj = list.get(i);
content[i][0] = obj.getId().toString();
content[i][1] = obj.getUsername();
content[i][2] = obj.getPassword();
content[i][3] = obj.getPhone();
content[i][4] = obj.getCreateTime().toString();
}
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送响应流方法
*/
public void setResponseHeader(HttpServletResponse response, String fileName) {
try {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.setContentType("application/octet-stream;charset=ISO8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
- Service层的编写
/**
* 测试POI导出用户列表来
* @return
*/
public interface UserService{
public List<PageData> serviceList();
}
- serviceList的实现类
/**
* 测试POI导出用户列表来
* @return
*/
public class UserServiceImpl implements UserService{
public List<PageData> serviceList() {
return userMapper.selectAll();
}
}
- dao层的编写
public interface UserMapper{
public List<PageDate> selectAll();
}
- entity实体类的编写
@Data
public class PageData {
private Long id;
private String username;
private String password;
private String phone;
private Date createTime;
}
- mapper文件的sql语句按前端传输的User类型
<select id= "selectAll" resultType="com.study.PageDate">
select id,user_name,password,phone,createTime from user
<include refid="sqlWhere"/>
order by id desc
</select>
<sql id="sqlWhere">
<where>
<if test="id!=null and id!=''">
and id = #{id}
</if>
<if test="loanId!=null and loanId!=''">
and user_name= #{username}
</if>
<if test="custNo!=null and custNo!=''">
and password= #{password}
</if>
<if test="loanId!=null and loanId!=''">
and phone= #{phone}
</if>
<if test="custNo!=null and custNo!=''">
and createtime = #{createTime }
</if>
</where>
</sql>
当前端导出大量数据可能造成浏览器的爆炸这样现在后端处理好直接在请求头中将表格传输过去 就能成功解决