详细学习可参考博客:Java导出Excel(Poi详解)_Action_Wang的博客-CSDN博客_poi导出excel
一、添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.0</version>
</dependency>
二、创建POIUtils工具类实现导出数据和导入数据工具类
public class POIUtils {
public static ResponseEntity<byte[]> employee2Excel(List<Employee> list) {
//1. 创建一个 Excel 文档
HSSFWorkbook workbook = new HSSFWorkbook();
//2. 创建文档摘要
workbook.createInformationProperties();
//3. 获取并配置文档信息
DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation();
//文档类别
docInfo.setCategory("员工信息");
//文档管理员
docInfo.setManager("javaboy");
//设置公司信息
docInfo.setCompany("www.javaboy.org");
//4. 获取文档摘要信息
SummaryInformation summInfo = workbook.getSummaryInformation();
//文档标题
summInfo.setTitle("员工信息表");
//文档作者
summInfo.setAuthor("javaboy");
// 文档备注
summInfo.setComments("本文档由 javaboy 提供");
//5. 创建样式
//创建标题行的样式
HSSFCellStyle headerStyle = workbook.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
HSSFCellStyle dateCellStyle = workbook.createCellStyle();
dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
HSSFSheet sheet = workbook.createSheet("员工信息表");
//设置列的宽度
sheet.setColumnWidth(0, 5 * 256);
sheet.setColumnWidth(1, 12 * 256);
sheet.setColumnWidth(2, 10 * 256);
sheet.setColumnWidth(3, 5 * 256);
sheet.setColumnWidth(4, 12 * 256);
sheet.setColumnWidth(5, 20 * 256);
sheet.setColumnWidth(6, 10 * 256);
sheet.setColumnWidth(7, 10 * 256);
sheet.setColumnWidth(8, 16 * 256);
sheet.setColumnWidth(9, 12 * 256);
sheet.setColumnWidth(10, 15 * 256);
sheet.setColumnWidth(11, 20 * 256);
sheet.setColumnWidth(12, 16 * 256);
sheet.setColumnWidth(13, 14 * 256);
sheet.setColumnWidth(14, 14 * 256);
sheet.setColumnWidth(15, 12 * 256);
sheet.setColumnWidth(16, 8 * 256);
sheet.setColumnWidth(17, 20 * 256);
sheet.setColumnWidth(18, 20 * 256);
sheet.setColumnWidth(19, 15 * 256);
sheet.setColumnWidth(20, 8 * 256);
sheet.setColumnWidth(21, 25 * 256);
sheet.setColumnWidth(22, 14 * 256);
sheet.setColumnWidth(23, 15 * 256);
sheet.setColumnWidth(24, 15 * 256);
//6. 创建标题行
HSSFRow r0 = sheet.createRow(0);
HSSFCell c0 = r0.createCell(0);
c0.setCellValue("编号");
c0.setCellStyle(headerStyle);