先引入pom
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
@Data
public class ExportExcelUtils<T> {
// 表头
private List<String> titles;
//实体类
private Class<T> clazz;
// 页签名称
private String name;
public void exportExcel(HttpServletResponse response, String fileName,List<T> data) throws Exception {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8"));
exportExcel(data, response.getOutputStream());
}
public void exportExcel(List<T> data, OutputStream out) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
try {
String sheetName = clazz.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
writeExcel(wb, sheet, data);
wb.write(out);
} finally {
wb.close();
}
}
private void writeExcel(XSSFWorkbook wb, Sheet sheet, List<T> data) {
int rowIndex = 0;
rowIndex = writeTitlesToExcel(wb, sheet, titles);
writeRowsToExcel(wb, sheet,obj2arr(data), rowIndex);
autoSizeColumns(sheet, titles.size() + 1);
}
private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) {
int rowIndex = 0;
int colIndex = 0;
Font titleFont = wb.createFont();
titleFont.setFontName("simsun");
titleFont.setBold(true);
// titleFont.setFontHeightInPoints((short) 14);
titleFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle titleStyle = wb.createCellStyle();
titleStyle.setAlignment(HorizontalAlignment.CENTER);
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
titleStyle.setFont(titleFont);
setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
Row titleRow = sheet.createRow(rowIndex);
// titleRow.setHeightInPoints(25);
colIndex = 0;
for (String field : titles) {
Cell cell = titleRow.createCell(colIndex);
cell.setCellValue(field);
cell.setCellStyle(titleStyle);
colIndex++;
}
rowIndex++;
return rowIndex;
}
private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<String[]> rows, int rowIndex) {
int colIndex = 0;
Font dataFont = wb.createFont();
dataFont.setFontName("simsun");
// dataFont.setFontHeightInPoints((short) 14);
dataFont.setColor(IndexedColors.BLACK.index);
XSSFCellStyle dataStyle = wb.createCellStyle();
dataStyle.setAlignment(HorizontalAlignment.CENTER);
dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
for (String[] rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
// dataRow.setHeightInPoints(25);
colIndex = 0;
for (String cellData : rowData) {
Cell cell = dataRow.createCell(colIndex);
if (cellData != null) {
cell.setCellValue(cellData.toString());
} else {
cell.setCellValue("");
}
cell.setCellStyle(dataStyle);
colIndex++;
}
rowIndex++;
}
return rowIndex;
}
private static void autoSizeColumns(Sheet sheet, int columnNumber) {
for (int i = 0; i < columnNumber; i++) {
int orgWidth = sheet.getColumnWidth(i);
sheet.autoSizeColumn(i, true);
int newWidth = (int) (sheet.getColumnWidth(i) + 100);
if (newWidth > orgWidth) {
sheet.setColumnWidth(i, newWidth);
} else {
sheet.setColumnWidth(i, orgWidth);
}
}
}
private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
style.setBorderTop(border);
style.setBorderLeft(border);
style.setBorderRight(border);
style.setBorderBottom(border);
style.setBorderColor(BorderSide.TOP, color);
style.setBorderColor(BorderSide.LEFT, color);
style.setBorderColor(BorderSide.RIGHT, color);
style.setBorderColor(BorderSide.BOTTOM, color);
}
public List<String[]> obj2arr(List<?> list) {
@SuppressWarnings("rawtypes")
Class cl = list.get(0).getClass();
System.out.println(cl.toString());
Field[] fields = cl.getDeclaredFields();
List<String[]> datas=new ArrayList<>();
for (Object li:list){
String[] strArr=new String[fields.length-1];//出去第一个序列化
for (int i = 1; i < fields.length; i++) {//第一个序列化属性没用
Field f = fields[i];
f.setAccessible(true); // 设置些属性是可以访问的
String key = f.getName();// key:得到属性名
//String type = f.getType().toString();// 得到此属性的类型
Object value =null;
try {
value = f.get(li);//获取值
if(f.getType().toString().contains("Date")){//日期转换
strArr[i-1]=new String(getStringDate(value));//数组从0开始
}else{
strArr[i-1]=new String(value+"");
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
datas.add(strArr);
}
return datas;
}
public String getStringDate(Object dataobj) {
Date date= (Date) dataobj;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(date);
return dateString;
}
public void getHead(){
List<String> titles = new ArrayList();
Field[] fields= clazz.getDeclaredFields();
for (int i=1;i<fields.length;i++){
titles.add(fields[i].getName());
}
this.setTitles(titles);
}
public ExportExcelUtils (Class clazz) {
this.clazz=clazz;
getHead();
// System.out.println(this.titles);
}
}
使用方法
1.必须接收HttpServletResponse
2.ExportExcelUtils<泛型类> data = new ExportExcelUtils(泛型类.class);
3.data.setName(“hello”);
4.data.exportExcel(response,“文件名”,list数据);
@RequestMapping(value = "/excel", method = RequestMethod.GET)
public void excel(HttpServletResponse response) throws Exception {
ExportExcelUtils<SysUser> data = new ExportExcelUtils(SysUser.class);
data.setName("hello");
List<SysUser> sysUsers= sysUserService.queryAll(new SysUser());
data.exportExcel(response,"hello.xlsx",sysUsers);
}