springboot 通用的导入和导出 代码简单方便
1.先写个 ExcelResources 类
package com.pengtu.utils.ExcelUtils;
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
int order() default 9999;//定义字段在excel的单元格列坐标位置
String title() default "";//定义列坐标对应的标题
int cloumn() default 100;//定义列宽
String pattern() default "";//定义日期显示格式
}
2.再写个导出的util
package com.pengtu.service.util;
import com.pengtu.Constants;
import com.pengtu.dao.govinvested.ProjectDao;
import com.pengtu.entity.govinvested.Project;
import com.pengtu.service.govinvested.ProjectService;
import com.pengtu.utils.ExcelUtils.ExcelResources;
import com.pengtu.utils.ExcelUtils.SexType;
import com.pengtu.utils.ExcelUtils.TitleAndCloumn;
import com.pengtu.utils.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import javax.persistence.Column;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import org.springframework.stereotype.Service;
@Service
public class ExcelService {
private static float title_row_height=30;//标题行高
private static float data_row_height=25;//数据行高
public void exportExcel(HttpServletRequest request, HttpServletResponse response, String fileName , List<?> excelDatas, Class<?> clz ) {
try {
HSSFWorkbook resultWb=new HSSFWorkbook();
HSSFSheet sheet=resultWb.createSheet();//创建sheet
//根据类类型信息获取导出的excel对应的标题和列宽 key-列号,value-标题和列宽
HashMap<Integer, TitleAndCloumn> orderTitleAndCloumnMap=getTitleAndCloumnMap(clz);
//设置列宽
orderTitleAndCloumnMap.forEach((k,v) -> {
sheet.setColumnWidth(k, v.getCloumn()*256);
});
HSSFRow row0=sheet.createRow(0);
//设置标题行高
row0.setHeightInPoints(title_row_height);
//创建标题单元格格式
HSSFCellStyle titleCellStyle=getCellStyle(resultWb,11,true,IndexedColors.BLACK.index);
//填充标题行内容
orderTitleAndCloumnMap.forEach((k,v) -> {
HSSFCell row0Cell=row0.createCell(k);
row0Cell.setCellValue(v.getTitle());
row0Cell.setCellStyle(titleCellStyle);
});
//创建正文单元格格式
HSSFCellStyle dataStyle = getCellStyle(resultWb,11,false, IndexedColors.BLACK.index);
//将正文转换为excel数据
int rowNum=1;
for(Object data:excelDatas){
HSSFRow row=sheet.createRow(rowNum++);
row.setHeightInPoints(data_row_height);
//获取对象值 key-列号 value-String值
HashMap<Integer,String> orderValueMap=getValueMap(data);
orderValueMap.forEach((k,v) ->{
HSSFCell cell=row.createCell(k);
cell.setCellValue(v);
cell.setCellStyle(dataStyle);
}
);
}
String downFileName=fileName+".xls";
response.setContentType("application/vnd.ms-excel; charset=UTF-8");// application/x-download
response.setHeader("Content-Disposition", "attachment; "
+encodeFileName(request, downFileName));
OutputStream outputStream = response.getOutputStream();
resultWb.write(outputStream);
outputStream.flush();
outputStream.close();
resultWb.close();
}catch (Exception e1) {
e1.printStackTrace();
}
}
/**
* 获取类的属性对应单元格标题和列宽
* @param
* @return
*/
private static HashMap<Integer, TitleAndCloumn> getTitleAndCloumnMap(Class<?> clz) {
HashMap<Integer, TitleAndCloumn> orderTitleAndCloumnMap=new HashMap<>();
Field[] fs = clz.getDeclaredFields();
for(Field f:fs) {
f.setAccessible(true);
if(f.isAnnotationPresent(ExcelResources.class)) {
Integer order=f.getAnnotation(ExcelResources.class).order();
String title=f.getAnnotation(ExcelResources.class).title();
int cloumn=f.getAnnotation(ExcelResources.class).cloumn();
TitleAndCloumn titleAndCloumn=new TitleAndCloumn(title,cloumn);
orderTitleAndCloumnMap.put(order,titleAndCloumn);
}
}
return orderTitleAndCloumnMap;
}
public HSSFCellStyle getCellStyle(HSSFWorkbook workbook,int fontSize,boolean isBoleaWeight,short color){
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
style.setBorderBottom(BorderStyle.THIN);
style.setBorderL