poi 导出Xlsx格式的excel 工具类,此类可以作为对封装好的poi包 如easypoi中的源码一起参考参考(有些小伙伴们可能看源码看的过程很头痛),有些小伙伴们想要一些样式、颜色设置,去参考吧
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class ExportExcelUtil<T> {
public ExportExcelUtil(){}
/**
由于不是封装好的,功能没有很强大,表头需要自己手动构建,并且不能和查出来的数据行错位
title 标题,head 表头 String[] headers = {菜品,图片,价格},
List<List<String>> dataCollection = new ArrayList()<数据行.size>。
dataCollection .add(数据行)
*/
public void exportExcel(String title, String[] headers, Collection<T> dataset,HttpServletResponse response) {
try {
response.setContentType("application/x-download");
response.setHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(title, "UTF-8"));
response.setHeader("fileName", URLEncoder.encode(title, "UTF-8"));
response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
response.setHeader("Access-Control-Allow-Headers","Content-Type,fileName,Content-Disposition");
response.flushBuffer();
exportExcelXlsx(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd");
} catch (IOException e1) {
log.error("",e1);
}
}
private void exportExcelXlsx(String title, String[] headers,
Collection<T> dataset, OutputStream out, String pattern) {
// 声明一个工作薄
// XSSFWorkbook workbook = new XSSFWorkbook();
SXSSFWorkbook workbook = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
// 生成一个表格
Sheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为20个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
CellStyle style = workbook.createCellStyle();
// 设置这些样式
java.awt.Color color = new java.awt.Color(192, 192, 192);
style.setFillForegroundColor(new XSSFColor(color).getIndex());
style.setAlignment(HorizontalAlignment.CENTER);
// 生成一个字体
Font font = workbook.createFont();
// java.awt.Color color1 = new java.awt.Color(255, 0, 255);
// font.setColor(new XSSFColor(color1).getIndex());
font.setBold(true);
font.setFontHeightInPoints((short) 12);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
CellStyle style2 = workbook.createCellStyle();
java.awt.Color color2 = new java.awt.Color(255, 255, 0);
style2.setFillForegroundColor(new XSSFColor(color2).getIndex());
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成另一个字体
Font font2 = workbook.createFont();
// font2.setBold(true);
// 把字体应用到当前的样式
style2.setFont(font2);
// 声明一个画图的顶级管理器
Drawing patriarch = sheet.createDrawingPatriarch();
// 产生表格标题行
Row row = sheet.createRow(0);
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(style);
XSSFRichTextString text = new XSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
Cell cell = null;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
T t = it.next();
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
if((i+1)>headers.length){
break;
}
cell = row.createCell(i);
cell.setCellStyle(style2);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName);
Object value = getMethod.invoke(t);
// 判断值的类型后进行强制类型转换
String textValue = "";
if (value instanceof Boolean) {
boolean bValue = (Boolean) value;
textValue = "是";
if (!bValue) {
textValue = "否";
}
} else if (value instanceof Date) {
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
// 有图片时,设置行高为60px
row.setHeightInPoints(60);
// 设置图片所在列宽度为80px,注意这里单位的一个换算
sheet.setColumnWidth(i, (short) (35.7 * 80));
byte[] bsValue = (byte[]) value;
ClientAnchor anchor = new XSSFClientAnchor(0, 0,
1023, 255, (short) 6, index, (short) 6, index);
anchor.setAnchorType(2);
patriarch.createPicture(anchor, workbook.addPicture(
bsValue, XSSFWorkbook.PICTURE_TYPE_JPEG));
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
} else {
textValue = "";
}
}
// 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
if (textValue != null) {
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
RichTextString richString = new XSSFRichTextString(
textValue);
richString.applyFont(font2);
cell.setCellValue(richString);
}
}
} catch (SecurityException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException | InvocationTargetException e) {
log.error(e.getMessage(),e);
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
log.error(e.getMessage(),e);
}
}
}