在springboot项目中,如何进行excel表格的导入导出功能?
以下是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。
1. 使用 Apache POI 实现 Excel 导入导出
添加依赖
在 pom.xml
中添加 Apache POI 的依赖:
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.2.3</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version>
</dependency>
实体类
public class User {private Long id;private String name;private Integer age;private String email;// 构造方法、getter 和 setter 方法public User() {}public User(Long id, String name, Integer age, String email) {this.id = id;this.name = name;this.age = age;this.email = email;}// getter 和 setter 方法省略
}
导出 Excel
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;public class ExcelUtil {public static void exportUserList(HttpServletResponse response, List<User> userList) {// 创建工作簿Workbook workbook = new HSSFWorkbook(); // 导出 .xls 文件,使用 XSSFWorkbook 导出 .xlsx 文件// 创建工作表Sheet sheet = workbook.createSheet("用户信息表");// 创建表头Row headerRow = sheet.createRow(0);String[] headers = {"ID", "姓名", "年龄", "邮箱"};for (int i = 0; i < headers.length; i++) {Cell cell = headerRow.createCell(i);cell.setCellValue(headers[i]);}// 填充数据for (int i = 0; i < userList.size(); i++) {User user = userList.get(i);Row dataRow = sheet.createRow(i + 1);dataRow.createCell(0).setCellValue(user.getId() == null ? "" : user.getId().toString());dataRow.createCell(1).setCellValue(user.getName() == null ? "" : user.getName());dataRow.createCell(2).setCellValue(user.getAge() == null ? "" : user.getAge().toString());dataRow.createCell(3).setCellValue(user.getEmail() == null ? "" : user.getEmail());}// 设置响应头response.setContentType("application/vnd.ms-excel");response.setCharacterEncoding("UTF-8");String fileName = "用户信息表.xls"; // 文件名try {response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));OutputStream outputStream = response.getOutputStream();workbook.write(outputStream);outputStream.flush();outputStream.close();workbook.close();} catch (Exception e) {e.printStackTrace();}}
}
导入 Excel
import org.apache.poi.ss.usermodel.*;
import org.springframework.web.multipart.MultipartFile;import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;public class ExcelImportUtil {public static List<User> importUserList(MultipartFile file) {List<User> userList = new ArrayList<>();try {// 获取文件流InputStream inputStream = file.getInputStream();// 创建工作簿Workbook workbook = WorkbookFactory.create(inputStream);// 获取第一个工作表Sheet sheet = workbook.getSheetAt(0);// 遍历行for (int i = 1; i <= sheet.getLastRowNum(); i++) { // 从第 2 行(索引 1)开始读取数据Row row = sheet.getRow(i);if (row == null) continue;// 获取单元格数据Long id = getCellValue(row.getCell(0));String name = getCellValue(row.getCell(1));Integer age = getCellValue(row.getCell(2));String email = getCellValue(row.getCell(3));// 创建 User 对象并添加到列表User user = new User(id, name, age, email);userList.add(user);}workbook.close();inputStream.close();} catch (Exception e) {e.printStackTrace();}return userList;}private static Long getCellValue(Cell cell) {if (cell == null) return null;if (cell.getCellType() == CellType.NUMERIC) {return (long) cell.getNumericCellValue();} else if (cell.getCellType() == CellType.STRING) {return Long.parseLong(cell.getStringCellValue());}return null;}private static String getCellValue(Cell cell) {if (cell == null) return null;if (cell.getCellType() == CellType.NUMERIC) {return String.valueOf((long) cell.getNumericCellValue());} else if (cell.getCellType() == CellType.STRING) {return cell.getStringCellValue();}return null;}
}
2. 使用 EasyExcel 实现 Excel 导入导出
添加依赖
在 pom.xml
中添加 EasyExcel 的依赖:
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>3.2.0</version>
</dependency>
实体类
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.format.NumberFormat;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight;import java.util.Date;public class PersonVO {@ExcelProperty(value = "姓名", index = 0)private String name;@ExcelProperty(value = "年龄", index = 1)@ColumnWidth(15)@NumberFormat("#")private Integer age;@ExcelProperty(value = "出生日期", index = 2)@DateTimeFormat("yyyy-MM-dd")private Date birthday;// getter 和 setter 方法省略
}
导出 Excel
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;public class ExcelExportUtil {public static void exportPersonList(HttpServletResponse response, List<PersonVO> personList) {String fileName = "人员信息表.xlsx";String sheetName = "人员信息表";try {// 设置响应头response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("UTF-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));OutputStream outputStream = response.getOutputStream();// 写入 Excel 文件EasyExcel.write(outputStream, PersonVO.class).sheet(sheetName).doWrite(personList);outputStream.flush();outputStream.close();} catch (Exception e) {e.printStackTrace();}}
}
导入 Excel
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;import javax.servlet.http.HttpServletRequest;
import java.util.List;public class ExcelImportUtil {public static List<PersonVO> importPersonList(MultipartFile file) {List<PersonVO> personList = new ArrayList<>();try {EasyExcel.read(file.getInputStream(), PersonVO.class, new ReadListener<PersonVO>() {@Overridepublic void invoke(PersonVO data, AnalysisContext analysisContext) {personList.add(data);}@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {}}).sheet().doRead();} catch (Exception e) {e.printStackTrace();}return personList;}
}
以上是使用 Apache POI 和 EasyExcel 实现 Excel 表格导入导出功能的具体代码示例。你可以根据实际需求选择合适的方法进行开发。