註解 :
import java.lang.annotation.*;
/**
* @author jly Exce註解
* @date 2018-11-30
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
@Documented
public @interface ExceDataName {
/**
* 字段名稱
* @return
*/
String name() default "未命名";
}
要導出vo,
public class OverdueData extends BaseQuery {
@ExceDataName(name = "註冊時間")
private String create_time;
@ExceDataName(name = "用戶來源")
private String source;
@ExceDataName(name = "用戶姓名")
private String real_name;
@ExceDataName(name = "用戶手機")
反射/導出核心代碼:
/**
* 導出下載Excel
*
* @param response
* @param fileName 文件名稱
* @param ExcelName 表名稱
* @param ts 數據 vo集合
* @throws Exception
*/
public static void exportExcel(HttpServletResponse response, String fileName, String ExcelName, List<Object> ts) throws Exception {
if (!ts.isEmpty()) {//表頭
Object t = ts.get(0);
Class cls = t.getClass();
ExcelData data = new ExcelData();
data.setName(ExcelName);
Field[] fieldlist = cls.getDeclaredFields();
//添加表頭
List<String> titles = new ArrayList();
for (int i = 0; i < fieldlist.length; i++) {
String fieldName = null;
Field fld = fieldlist[i];
//打開私有訪問
fld.setAccessible(true);
Annotation[] allAnnotations = fld.getAnnotations();
for (Annotation an : allAnnotations) {//字段上的所有註解,沒有加該註解的字段直接跳過
Class annotationType = an.annotationType();
ExceDataName name = fld.getAnnotation(ExceDataName.class);
if (name != null) {
fieldName = name.name();
} else {
continue;
}
}
if (null == fieldName) {
continue;
}
titles.add(fieldName);
}
data.setTitles(titles);
//添加列
List<List<Object>> rows = new ArrayList();
for (Object o : ts) {
Class clss = o.getClass();
Field[] fieldlists = clss.getDeclaredFields();
List<Object> row = new ArrayList<>();
for (int i = 0; i < fieldlists.length; i++) {
Field fld = fieldlists[i];
//打開私有訪問
fld.setAccessible(true);
String fieldName = null;
//打開私有訪問
fld.setAccessible(true);
Annotation[] allAnnotations = fld.getAnnotations();
for (Annotation an : allAnnotations) {
Class annotationType = an.annotationType();
ExceDataName name = fld.getAnnotation(ExceDataName.class);
if (name != null) {
fieldName = name.name();
} else {
continue;
}
}
if (null == fieldName) {
continue;
}
//獲取屬性值
Object value = fld.get(o);
row.add(fld.get(o));
}
rows.add(row);
}
data.setRows(rows);
SimpleDateFormat fdate = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
if (null == fileName) {//沒有名稱默認成日期
fileName = fdate.format(new Date()) + ".xls";
} else {
fileName = fileName + ".xls";
}
ExportExcelUtils.exportExcel(response, fileName, data);
}
}
public static void exportExcel(HttpServletResponse response, String fileName, ExcelData 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 static void exportExcel(ExcelData data, OutputStream out) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
try {
String sheetName = data.getName();
if (null == sheetName) {
sheetName = "Sheet1";
}
XSSFSheet sheet = wb.createSheet(sheetName);
writeExcel(wb, sheet, data);
wb.write(out);
} finally {
wb.close();
}
}
private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {
int rowIndex = 0;
rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
writeRowsToExcel(wb, sheet, data.getRows(), rowIndex);
autoSizeColumns(sheet, data.getTitles().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(XSSFCellStyle.ALIGN_CENTER);
titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
titleStyle.setFillPattern(XSSFCellStyle.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<List<Object>> 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(XSSFCellStyle.ALIGN_CENTER);
dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
dataStyle.setFont(dataFont);
setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));
for (List<Object> rowData : rows) {
Row dataRow = sheet.createRow(rowIndex);
// dataRow.setHeightInPoints(25);
colIndex = 0;
for (Object 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);
}
控制層方法: 數據庫查出要導出的數據---導出 ExportExcelUtils.exportExcel(response, "逾期數據", "逾期數據", queryDataMapper.queryOverdueData(overdueData));
代碼下載地址:https://download.csdn.net/download/jialiuyang/10821394