基于POI导出Excel开发
流程概述
1.添加依赖
2.controller层编写
一,依赖添加
依赖添加如下:
org.apache.poi poi 3.9 org.apache.poi poi-ooxml 3.9 org.apache.poi poi-ooxml-schemas 3.9 ``` ``` 二,Controller层编写
/**
* 导出信用承诺统计信息为excel文件
* @param request
* @return
*/
@RequestMapping("/outPutXycnExcel")
public void outPutXycnExcel(){
//第一步,创建一个HSSFWorkbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,为工作簿创建一个新工作表,传入表名
HSSFSheet sheet = wb.createSheet("信用承诺统计");
// 第三步,在sheet中添加表头第0行
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格样式,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 创建一个居中格式
//第五步创建字体样式
Font headerFont = wb.createFont();//创建一个字体
headerFont.setFontName("Arial");//设置字体的名称(如Arial)
headerFont.setFontHeightInPoints((short) 12);//设置字体高度
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);//设置字体加粗
headerFont.setColor(HSSFColor.BLACK.index);//设置字体的颜色
style.setFont(headerFont);//应用该字体
//创建一个合并的单元格对象
sheet.addMergedRegion(new CellRangeAddress(0,0,0,2));//创建合并的单元格范围
//在行中创建新的单元格并返回
HSSFCell cell = row.createCell(0);
cell.setCellValue("导出表单测试");//添加标题
cell.setCellStyle(style);//将样式赋值
//写入execl列标题
//创建标题行
row = sheet.createRow(1);
//标题数据
String[] title = {"测试列1","测试列2","测试列3"};
for(int i=0;i<title.length;i++){
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
sheet.setColumnWidth(i, 20 * 256);
}
//创建内容
String[] [] values = {{"11","12","13"},{"21","22","23"},{"31","32","33"}};
for(int i=0;i<values.length;i++){
row = sheet.createRow(i + 2);//创建数据行
for(int j=0;j<values[i].length;j++){
//将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
HttpServletResponse response = getResponse();
//发送回浏览器
try (OutputStream os = response.getOutputStream();){//从response中获取输出流
String fileName = new String("测试导出Excel.xls".getBytes(), "ISO8859-1");//准备好文件名
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");
wb.write(os);//写出到浏览器
os.close();//关闭流
} catch (IOException e) {
e.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
}