导出excel是我们经常会碰到的需求,找了网上的很多资料,太乱了,不太理想,最后索性自己整理了一份。
现在用的比较多的就是POI了,我在项目中用的还是旧版本的3.16
1:首先我们需要在pom.xml文件里导入maven依赖
org.apache.poi
poi
3.16
2:通用的excelUtil(关键)
package com.domain.domaindetection.exhibion.util;
import org.apache.poi.hssf.usermodel.*;
public class ExcelUtil {
/**
* 导出Excel.xls 下一个方法是导出后缀为 .xlsx的
*
* @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;
}
}
/**
* 导出Excel.xlsx
*
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
* @return
*/
public static XSSFWorkbook getXSSFWorkbook(String sheetName, String[] title, String[][] values, XSSFWorkbook wb) {
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if (wb == null) {
wb = new XSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
XSSFSheet sheet = wb.createSheet(sheetName);
//自适应单元格
//sheet.autoSizeColumn(1, true);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
XSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
XSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
//声明列对象
XSSFCell 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]);
}
}
for (int i = 0; i < title.length; i++) {
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 15 / 10);
}
return wb;
}
3:接下来就是我们的业务代码啦,根据自己的需求增加相应的标题、文件名、sheet名,里面的内容是我自己测试的数据
package com.domain.domaindetection.exhibion.controller;
import com.domain.domaindetection.exhibion.service.ThirteenRootService;
import com.domain.domaindetection.exhibion.util.ExcelUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
@RestController
@CrossOrigin
@RequestMapping(value = “/thirteen”)
public class ExcelController {
@Autowired
private ThirteenRootService thirteenRootService;
/**
* 导出报表 这个接口暂时没用到
*/
@RequestMapping(value = "/export")
public void export(@RequestParam String times, HttpServletResponse response) throws Exception {
//获取数据
List<Map<String, Object>> list = thirteenRootService.getAllRoot(times);
//excel标题
String[] title = {"名称", "类型", "ip", "运营商", "信息"};
//excel文件名
String fileName = "信息报表" + System.currentTimeMillis() + ".xls";
//sheet名
String sheetName = "信息报表";
String[][] content = new String[list.size()][];
for (int i = 0; i < list.size(); i++) {
content[i] = new String[title.length];
Map<String, Object> obj = list.get(i);
content[i][0] = (String) obj.get("m");
content[i][1] = (String) obj.get("l");
content[i][2] = (String) obj.get("i");
content[i][3] = (String) obj.get("y");
content[i][4] = (String) obj.get("x");
}
//创建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 static void setResponseHeader(HttpServletResponse response, String fileName) {
try {
fileName = new String(fileName.getBytes(), "ISO8859-1");
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
ok大功告成