Java导出Excel(附完整源码)
前言
导出excel是咱Java开发的必备技能啦,之前项目有这个功能,现在将其独立出来,分享一下。
所用技术就是SpringBoot,然后是MVC架构模式。
废话不多说,直接上代码了,源码点末尾链接就可以下载
1. idea创建spring boot项目
新建一个SpringBoot项目(可以官网https://start.spring.io/直接生成下载,然后导入idea),项目结构如下:
2. 修改pom文件,添加依赖;
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 导出excel -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-contrib -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-contrib</artifactId>
<version>3.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-scratchpad -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
3. 新建一个实体类,命名为User.java;
package com.wajpzywj.exceldemo.vo;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = -9180229310895087286L;
private String name; // 姓名
private String sex; // 性别
private Integer age; // 年龄
private String phoneNo; // 手机号
private String address; // 地址
private String hobby; // 爱好
public User(String name, String sex, Integer age, String phoneNo, String address, String hobby) {
this.name = name;
this.sex = sex;
this.age = age;
this.phoneNo = phoneNo;
this.address = address;
this.hobby = hobby;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}