使用easypoi快速导出excel
新建springboot工程
pom
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.jeecg</groupId> <artifactId>easypoi-base</artifactId> <version>2.4.0</version> </dependency>
新建model
@Entity
@Table
@ExcelTarget(value = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long uid;
@Excel(name = "学生账号", orderNum = "1", width = 25,height = 15)
private String username;
@Excel(name = "年龄", orderNum = "2", width = 25,height = 15)
private int age;
public long getUid() {
return uid;
}
public void setUid(long uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
repository
@Repository
public interface Userrepository extends JpaRepository<User, Long> {
}
controller
@Controller
public class UserController {
@Autowired
Userrepository userrepository;
@GetMapping(value = "/export")
public void export(HttpServletResponse response) throws IOException {
StringBuffer sb = new StringBuffer();
String excelname = new String(sb.append("用户统计").toString().getBytes("gbk"), "iso8859-1");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + excelname + ".xls");
OutputStream os = null;
List<User> userList = userrepository.findAll();
try {
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), User.class, userList);
//设置样式
Sheet sheet = workbook.getSheet("Sheet0");//默認sheet的名字
Row row = sheet.getRow(0); //取XSL文件Sheet1页上第1行
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setFontHeightInPoints((short)18); //字体大小
font.setFontName("楷体");
font.setBold(true);
font.setColor(HSSFColor.RED.index); //紅色字
cellStyle.setFont(font);
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
cellStyle.setAlignment(HorizontalAlignment.CENTER);
int cells = row.getPhysicalNumberOfCells();
for (int i=0;i<cells ;i++){
row.getCell(i).setCellStyle(cellStyle);
}
os = new BufferedOutputStream(response.getOutputStream());
workbook.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
os.flush();
os.close();
}
}
}
本文介绍如何使用Easypoi库在Spring Boot项目中实现Excel的快速导出功能。具体步骤包括:配置pom.xml引入所需依赖、定义实体类、创建Repository接口以及Controller控制器来处理导出逻辑。

2165

被折叠的 条评论
为什么被折叠?



