POI导出数据到Excel
简介
自定义工具类源码:
public class WriterExcelUtils{
private WriterExcelUtils(){}
public static Workbook createWorkbook(String type){
Workbook workbook = null;
if ("xls".equalsIgnoreCase(type)){
workbook = new HSSFWorkbook();
}else if ("xlsx".equalsIgnoreCase(type)){
workbook = new SXSSFWorkbook();
}
return workbook;
}
public static CellStyle setCellStyle(Workbook workbook){
return workbook.createCellStyle();
}
public static Sheet createSheet(Workbook workbook, List<String> head, Short rowHeight, Integer columnWidth, CellStyle cellStyle){
Sheet sheet = workbook.createSheet();
sheet.setDefaultRowHeight(rowHeight);
Row row = sheet.createRow(0);
if (cellStyle != null) {
for (int i = 0; i < head.size(); i++) {
sheet.setColumnWidth(i, columnWidth);
Cell cell = row.createCell(i);
cell.setCellValue(head.get(i));
cell.setCellStyle(cellStyle);
}
}else{
for (int i = 0; i < head.size(); i++) {
sheet.setColumnWidth(i, columnWidth);
Cell cell = row.createCell(i);
cell.setCellValue(head.get(i));
}
}
return sheet;
}
private static <T> void exportDataToRow(T t, Row row, Integer size, CellStyle cellStyle) throws InvocationTargetException, IllegalAccessException, InstantiationException {
Class clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
Method[] methods = clazz.getMethods();
for (int i = 0; i < size; i++) {
String fieldName = fields[i].getName();
String str = fieldName.substring(0,1).toUpperCase().concat(fieldName.substring(1).toLowerCase());
String methodName = "get" + str;
Cell cell = row.createCell(i);
if (cellStyle != null) {
for (Method method : methods) {
if (methodName.equals(method.getName())){
cell.setCellValue(String.valueOf(method.invoke(t)));
cell.setCellStyle(cellStyle);
break;
}
}
}else{
for (Method method : methods) {
if (methodName.equals(method.getName())){
cell.setCellValue(String.valueOf(method.invoke(t)));
break;
}
}
}
}
}
public static <T> Workbook writeExcel(Sheet sheet, List<T> dataList, CellStyle cellStyle){
Workbook workbook = sheet.getWorkbook();
AtomicInteger rowCount = new AtomicInteger(1);
dataList.forEach(t ->{
if (t == null){
return;
}
Row row = sheet.createRow(rowCount.getAndIncrement());
try {
exportDataToRow(t, row, sheet.getRow(0).getPhysicalNumberOfCells(), cellStyle);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
});
return workbook;
}
public static void getExcel(String path, Workbook workbook) throws IOException {
OutputStream os = null;
try {
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
os = new FileOutputStream(file);
workbook.write(os);
os.flush();
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
if (workbook != null){
workbook.close();
}
if (os != null){
os.close();
}
}
}
public static void getExcel(HttpServletRequest request, HttpServletResponse response, Workbook workbook) throws IOException {
OutputStream os = null;
try {
String fileName = "数据信息" + ".xlsx";
fileName = new String(fileName.getBytes("UTF-8"), "iso8859-1");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/x-download");
response.setCharacterEncoding("UTF-8");
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
response.flushBuffer();
os = response.getOutputStream();
workbook.write(os);
os.flush();
}catch (Exception e){
System.out.println(e.getMessage());
}finally {
if (workbook != null){
workbook.close();
}
if (os != null){
os.close();
}
}
}
}
使用步骤
- 导入依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
- 申明Excel文档的头部信息
List<String> head = new ArrayList<>();
head.add("序号");
head.add("姓名");
head.add("年龄");
head.add("电话");
- 获取数据集合
List<User> data = new ArrayList<>();
data.add(new User((long) 1, "张三", 25, "13281815055"));
data.add(new User((long) 2, "李四", 22, "110"));
data.add(new User((long) 3, "王五", 21, "1231543134"));
- 根据工作簿后缀名创建工作簿(参数为“xls”或“xlsx”)
Workbook workbook = WriterExcelUtils.createWorkbook("xlsx");
- 创建一个Sheet页对象,设置头部信息以及头部单元格行高和列宽,CellStyle为null时单元格格式为默认格式
Sheet sheet = WriterExcelUtils.createSheet(workbook, head, (short) 400, 4000, null);
- 获取已经封装好数据的工作簿对象
Workbook workbook1 = WriterExcelUtils.writeExcel(sheet, data, null);
- 获取Excel文档(当参数为String,Workbook时,导出文档到指定目录;当参数为HttpServletRequest,HttpServletResponse,Workbook),导出文档到浏览器
WriterExcelUtils.getExcel("C:/Users/admin/Desktop/测试.xlsx",workbook1);