1.实体转换
/**
* 数据转换方法,实体字段应保持一致
* @param sources
* @param sourceClass
* @param targetClass
* @return
*/
public static List exchange(List sources,Class sourceClass,Class targetClass){
try {
Field[] fields = targetClass.getDeclaredFields();
List<Object> objects = new ArrayList<>();
for (Object source : sources) {
Object o = targetClass.newInstance();
for (Field field : fields) {
String name = field.getName();
String sourceMethodName = "get" + Character.toUpperCase(name.charAt(0)) + name.substring(1, name.length());
String targetMethodName = "set" + Character.toUpperCase(name.charAt(0)) + name.substring(1, name.length());
Method sourceMethod = sourceClass.getDeclaredMethod(sourceMethodName);
sourceMethod.setAccessible(true);
Object invoke = sourceMethod.invoke(source);
Method targetMethod = targetClass.getDeclaredMethod(targetMethodName,invoke.getClass());
targetMethod.setAccessible(true);
targetMethod.invoke(o, invoke);
}
objects.add(o);
}
return objects;
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
2.poi导出
/**
* 返回文件流
* @param wb
* @param response
* @param title
* @param suffix
* @throws IOException
*/
public static void writeWorkBook(Workbook wb, HttpServletResponse response, String title,String suffix) throws IOException {
OutputStream stream = null;
try {
stream = response.getOutputStream();
title = StringUtils.isNullOrEmpty(title) ? wb.getSheetAt(0).getSheetName() : title;
response.setContentType("application/ms-excel;charset=UTF-8");
response.setHeader("Content-Type", "application/octet-stream");
String fileName = title.concat(new SimpleDateFormat("_yyyyMMddHHmmss_").format(new Date())).concat(UUID.randomUUID().toString().substring(0, 8)).concat(suffix);
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
wb.write(stream);
stream.flush();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Workbook createHSSFWorkbook(String title, List<String> subtitle, List<String> attributes, List data){
Workbook workBook = new HSSFWorkbook();
return createWorkbook(workBook,title,subtitle,attributes,data);
}
public static Workbook createXSSFWorkbook(String title, List<String> subtitle, List<String> attributes, List data){
Workbook workBook = new SXSSFWorkbook();
return createWorkbook(workBook,title,subtitle,attributes,data);
}
/**
*
* @param wb Workbook对象
* @param title 一级标题
* @param subtitle 二级标题
* @param attributes 二级标题对应字段
* @param data 源数据
* @return
*/
private static Workbook createWorkbook(Workbook wb, String title, List<String> subtitle, List<String> attributes, List data){
int rowNum = 0;
Sheet sheet = wb.createSheet(title);
Row rowTitle = sheet.createRow(rowNum++);
CellStyle titleCellStyle = createTitleCellStyle(wb);
Cell cell = rowTitle.createCell(0);
cell.setCellValue(title);
cell.setCellStyle(titleCellStyle);
int titleSize = subtitle.size()-1;
sheet.addMergedRegion(new CellRangeAddress(0,0,0,titleSize));
Row rowSubTitle = sheet.createRow(rowNum++);
CellStyle titleSubCellStyle =createSubTitleCellStyle(wb);
fullTitle(rowSubTitle,titleSubCellStyle,subtitle);
CellStyle cellstyle = createCellStyle(wb);
try {
if(data != null){
if(subtitle.size() != attributes.size()){
throw new RuntimeException("表格列和字段列不匹配");
}
Row rowFile = null;
for (int i=0;i<data.size();i++) {
//创建行对象
rowFile = sheet.createRow(rowNum++);
Object object = data.get(i);
Class clazz = object.getClass();
for (int j = 0; j < attributes.size(); j++) {
String methodName = "get" + Character.toUpperCase(attributes.get(j).charAt(0)) + attributes.get(j).substring(1, attributes.get(j).length());
Method method = clazz.getDeclaredMethod(methodName);
method.setAccessible(true);
String returnName = method.getReturnType().getName();
if ("java.lang.String".equals(returnName)) {
//创建单元格对象
Cell cellFile = rowFile.createCell(j);
setCellStyleWithStyleAndValue(cellstyle, cellFile, method.invoke(object) == null ? "" : method.invoke(object).toString());
}
if ("java.util.Date".equals(returnName)) {
//创建单元格对象
Cell cellFile = rowFile.createCell(j);
Object invoke = method.invoke(object);
Date date = (Date) invoke;
setCellStyleWithStyleAndValue(cellstyle, cellFile, DateUtil.formatDate(date,"yyyy-MM-dd"));
}
if ("java.math.BigDecimal".equals(returnName)) {
//创建单元格对象
Cell cellFile = rowFile.createCell(j);
Object invoke = method.invoke(object);
BigDecimal bigDecimal = (BigDecimal) invoke;
setCellStyleWithStyleAndValue(cellstyle, cellFile, bigDecimal);
}
if ("java.lang.Integer".equals(returnName)) {
//创建单元格对象
Cell cellFile = rowFile.createCell(j);
Object invoke = method.invoke(object);
Integer integer = (Integer) invoke;
setCellStyleWithStyleAndValue(cellstyle, cellFile, String.valueOf(integer));
}
}
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return wb;
}
private static Row fullTitle(Row row, CellStyle titleCellStyle, List<String> titleNameList) {
Cell cell = null;
for (int i = 0; i < titleNameList.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(titleNameList.get(i));
cell.setCellStyle(titleCellStyle);
}
return row;
}
/**
* 创建一级标题单元格格式
* @param wb
* @return
*/
private static CellStyle createTitleCellStyle(Workbook wb) {
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setFillBackgroundColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex());
Font font = wb.createFont();
font.setFontHeightInPoints((short)20);
cellStyle.setFont(font);
return cellStyle;
}
/**
* 创建二级标题单元格格式
* @param wb
* @return
*/
private static CellStyle createSubTitleCellStyle(Workbook wb) {
CellStyle cellStyle = null;
cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_25_PERCENT.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
Font font = wb.createFont();
font.setColor(HSSFColor.HSSFColorPredefined.GREEN.getIndex());
font.setFontHeightInPoints((short)9);
cellStyle.setFont(font);
return cellStyle;
}
/**
* 创建三级标题单元格格式
* @param wb
* @return
*/
private static CellStyle createCellStyle(Workbook wb) {
CellStyle cellStyle = null;
cellStyle = wb.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
cellStyle.setBorderBottom(BorderStyle.THIN);
cellStyle.setBorderLeft(BorderStyle.THIN);
cellStyle.setBorderRight(BorderStyle.THIN);
cellStyle.setBorderTop(BorderStyle.THIN);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, String value){
cell.setCellStyle(style);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, Date value){
cell.setCellStyle(style);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, Integer value){
cell.setCellStyle(style);
cell.setCellValue(value);
return cell;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, BigDecimal value){
cell.setCellStyle(style);
cell.setCellValue(JSON.toJSONString(value));
return cell;
}
private static Cell setCellStyleWithStyleAndValue(CellStyle style, Cell cell, Object value){
cell.setCellStyle(style);
cell.setCellValue(JSON.toJSONString(value));
return cell;
}
导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
js处理blob
//导出数据
exportData:function(){
var origin = window.document.location.origin;//获取机器ip
var url = origin + "方法路由";
var data = JSON.stringify(this.searchModel);//请求参数
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/json");
//xhr.setTimeout(60000);
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
var blobUrl = window.URL.createObjectURL(new Blob([this.response]));
var link = document.createElement('a');
link.style.display = 'none';
link.href = blobUrl;
var filename = decodeURI(this.getResponseHeader("Content-Disposition").split(';')[1].split('filename=')[1]);
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(url.href);
document.body.removeChild(link);
};
// 发送ajax请求
xhr.send(data);
},