将数据库查询的信息导出到Excel
生成Excel及数据
public class ExportExcel<T> {
public void exportExcel(String title, String[] headers, Collection<T> list, List<String> containBean, OutputStream out) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle style = getHssfCellStyleOne(workbook);
HSSFSheet sheet = getHSSFSheet(title, headers, workbook, style);
HSSFCellStyle style2 = getHssfCellStyleTwo(workbook);
getRows(headers, style, sheet);
HSSFRow row;
try {
Iterator<T> it = list.iterator();
int index = 1;
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) it.next();
Field[] fields = t.getClass().getDeclaredFields();
if (CollectionUtils.isNotEmpty(containBean)) {
for (int j = 0; j < containBean.size(); j++) {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (!field.getName().equals(containBean.get(j)))
continue;
setCellValue(style2, t, field, row, j, font3);
}
}
} else {
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
setCellValue(style2, t, field, row, i, font3);
}
}
}
} catch (Exception e) {
logger.error("写数据到excel失败,title" + title, e);
} finally {
}
try {
workbook.write(out);
} catch (IOException e) {
logger.error("导出文件失败", e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
logger.error("关闭流失败", e);
}
}
}
}
}
将数据写入到Excel
public void writeExcel(String excelName, String[] headers, Collection<T> list, List<String> containBean, HttpServletResponse response) {
try {
String codedFileName = URLEncoder.encode(excelName, "UTF-8");
response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
OutputStream os = response.getOutputStream();
exportExcel(excelName, headers, list, containBean, os);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
生成Excel和一种字体
private HSSFCellStyle getHssfCellStyleOne(HSSFWorkbook workbook) {
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
return style;
}
生成Excel表及表头数据
private HSSFSheet getHSSFSheet(String title, String[] headers, HSSFWorkbook workbook, HSSFCellStyle style) {
HSSFSheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth((short) 15);
sheet.addMergedRegion(new Region(0, (short) 0, 0, (short) (headers.length - 1)));
HSSFRow rowTitle = sheet.createRow(0);
HSSFCell cellTitle = rowTitle.createCell(0);
cellTitle.setCellStyle(style);
HSSFRichTextString textTitle = new HSSFRichTextString(title);
cellTitle.setCellValue(textTitle);
return sheet;
}
生成字体
private HSSFCellStyle getHssfCellStyleTwo(HSSFWorkbook workbook) {
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
style2.setFont(font2);
return style2;
}
生成表格标题行
private HSSFRow getRows(String[] headers, HSSFCellStyle style, HSSFSheet sheet) {
HSSFRow row = sheet.createRow(1);
for (short i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(style);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
return row;
}
设置每一行中的列
private void setCellValue(HSSFCellStyle style2, T t, Field field, HSSFRow row, int index, HSSFFont font3) {
HSSFCell cell = row.createCell(index);
cell.setCellStyle(style2);
Object value = invoke(t, field);
String textValue = null;
if (value != null) {
if (value instanceof Date) {
Date date = (Date) value;
textValue = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
} else {
textValue = value == null ? "" : value.toString();
}
}
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
cell.setCellValue(Double.parseDouble(textValue));
} else {
HSSFRichTextString richString = new HSSFRichTextString(textValue);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
}
反射映射数据集字段
private Object invoke(T t, Field field) {
try {
String fieldName = field.getName();
PropertyDescriptor pd = new PropertyDescriptor(fieldName, t.getClass());
Method method = pd.getReadMethod();
return method.invoke(t);
} catch (Exception e) {
return null;
}
}
使用实例
ExportExcel<要导出的类> exportExcel = new ExportExcel<>();
String[] headers = new String[]{"Excel的表头1", "Excel的表头2", "Excel的表头3", "Excel的表头4"};
List<String> beans = Arrays.asList("要导出的类的字段", "位置和上面对应", "一一对应", "字段");
exportExcel.writeExcel("给Excel取个名字", headers, list, beans, response);