關於easypoi可參考http://doc.wupaas.com/docs/easypoi/easypoi-1c0u4mo8p4ro8
下面是在網上看過的總結比較好的導出操作:
准備工作:在pom.xml中引入相關依賴
<!-- easy-poi -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.1.0</version>
</dependency>
下面給出四種導出excel的用法示例:
示例一:直接將List<Map<String, Object>>數據導出為excel示例(無需模板):
/**
* 直接導出(無需模板)
* 注:此方式存在一些不足之處,在對性能、excel要求比較嚴格時不推薦使用
*/
@Test
public void directExportExcel() throws IOException {
// Map作為每一行的數據容器,List作為行的容器
List<Map<String, Object>> rowDataList = new ArrayList<>();
// 每個ExcelExportEntity存放Map行數據的key
List<ExcelExportEntity> keyList = new ArrayList<>();
Map<String, Object> aRowMap;
final int COMMON_KEY_INDEX = 10;
for (int i = 0; i < 5; i++) {
// 一個Map對應一行數據(如果需要導出多行數據,那么需要多個Map)
aRowMap = new HashMap<>(16);
for (int j = 0; j < COMMON_KEY_INDEX; j++) {
String key = j + "";
aRowMap.put(key, "坐標為(" + i + "," + j + ")");
}
rowDataList.add(aRowMap);
// 同一列對應的cell,在從Map里面取值時,會共用同一個key
// 因此ExcelExportEntity的個數要保持和列數做多的行 的map.size()大小一致
if (i == 0) {
ExcelExportEntity excelExportEntity;
for (int j = 0; j < COMMON_KEY_INDEX; j++) {
excelExportEntity = new ExcelExportEntity();
excelExportEntity.setKey(j + "");
// 設置cell寬
excelExportEntity.setWidth(15D);
// 設置cell是否自動換行
excelExportEntity.setWrap(true);
keyList.add(excelExportEntity);
}
}
}
// excel總體設置
ExportParams exportParams = new ExportParams();
// 不需要標題
exportParams.setCreateHeadRows(false);
// 指定sheet名字
exportParams.setSheetName("直接導出數據測試");
// 生成workbook 並導出
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, keyList, rowDataList);
File savefile = new File("C:/Users/JustryDeng/Desktop/");
if (!savefile.exists()) {
boolean result = savefile.mkdirs();
System.out.println("目錄不存在,創建" + result);
}
FileOutputStream fos = new FileOutputStream("C:/Users/JustryDeng/Desktop/abc.xls");
workbook.write(fos);
fos.close();
}
示例二:通過注解,直接將Object(集合)數據導出為excel示例(無需模板):
相關的SchoolVO模型為:
import cn.afterturn.easypoi.excel.annotation.Excel;
/**
* 學校模型
*/
public class SchoolVO {
/** 學校名稱 */
@Excel(name = "學校名稱", orderNum = "6", width = 20)
private String schoolName;
/** 學校地址 */
@Excel(name = "學校地址", orderNum = "8", width = 20)
private String schoolAddress;
}
相關的StudentVO模型為:
import cn.afterturn.easypoi.excel.annotation.Excel;
import java.util.Date;
/**
* Student數據模型
*
*/
public class StudentVO extends SchoolVO {
/**
* name指定導出excel時生成的列名
* orderNum可指定導出的該屬性對應的所在列的位置
* width設置單元格寬度
* type設置導出類型 1是文本, 2是圖片, 3是函數,10 數字 默認是文本
*/
@Excel(name = "學號", orderNum = "1", type = 10, width = 15)
private String studentID;
@Excel(name = "姓名", orderNum = "2", width = 15)
private String name;
/**
* 當gender為1時,導出的結果為 男, 當gender為0時,導出的結果為 女
* mergeVertical設置是否縱向合並列
*/
@Excel(name = "性別",mergeVertical = true, replace = {"男_1", "女_0"},orderNum = "3", width = 5)
private Integer gender;
/**
* type設置導出類型 1是文本, 2是圖片, 3是函數,10 數字 默認是文本
*/
@Excel(name = "年齡",orderNum = "4", type = 10, width = 5)
private int age;
/**
* 將Data日期導出為yyyy-MM-dd格式
* mergeVertical設置是否縱向合並列
* mergeRely設置合並列的前提條件,即:只有當索引為2的列(即:"性別"列)已經
* 合並了時,那么此時這一列的縱向相同時,才能縱向合並;如果引為2的
* 列(即:"性別"列)縱向數據不同,那么就算此列的縱向數據相同,那么
* 也不會合並
*/
@Excel(name = "入校時間",mergeVertical = true, mergeRely = {2}, format = "yyyy-MM-dd", orderNum = "5", width = 20)
private Date entranceTime;
@Excel(name = "班級",orderNum = "7", width = 15)
private String className;
/**
* 無參構造
*/
public StudentVO() {
}
/**
* 全參構造
*/
public StudentVO(String studentID, String name, Integer gender,
int age, Date entranceTime, String className) {
this.studentID = studentID;
this.name = name;
this.gender = gender;
this.age = age;
this.entranceTime = entranceTime;
this.className = className;
}
}
導出excel的測試方法為:
/**
* 對象---直接導出(無需模板)
*
* 注:如果模型 的父類的屬性也有@Excel注解,那么導出excel時,會連該模型的父類的屬性也一會兒導出
*
*/
@Test
public void directExportExcelByObject() throws IOException {
List<StudentVO> list = new ArrayList<>(16);
StudentVO student;
Random random = new Random();
for (int i = 0; i < 10; i++) {
student = new StudentVO(i + "",
"name" + i,
random.nextInt(2),
random.nextInt(100),
new Date(),
"className" + i);
student.setSchoolName("學校名稱" + i);
student.setSchoolAddress("學校地址" +i);
list.add(student);
}
ExportParams exportParams = new ExportParams();
exportParams.setSheetName("我是sheet名字");
// 生成workbook 並導出
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, StudentVO.class, list);
File savefile = new File("C:/Users/JustryDeng/Desktop/");
if (!savefile.exists()) {
boolean result = savefile.mkdirs();
System.out.println("目錄不存在,創建" + result);
}
FileOutputStream fos = new FileOutputStream("C:/Users/JustryDeng/Desktop/student.xls");
workbook.write(fos);
fos.close();
}
示例三:使用模板將Map<String, Object>數據導出為excel示例(需要模板
導出excel的測試方法為:
/**
* 模板導出---Map組裝數據
*
* 注:.xls的模板可以導出.xls文件,也可以導出xlsx的文件;
* 同樣的, .xlsx的模板可以導出.xls文件,也可以導出xlsx的文件;
*
*/
@Test
public void templateExportExcelByMap() throws IOException {
// 加載模板
TemplateExportParams params = new TemplateExportParams("templates/templateMap.xls");
Map<String, Object> map = new HashMap<>(16);
map.put("title", "全亞洲,最帥氣人員名單");
map.put("date", "2018-12-05");
map.put("interviewer", "JustryDeng");
List<Map<String, Object>> list = new ArrayList<>(16);
Map<String, Object> tempMap;
for (int i = 0; i < 5; i++) {
tempMap = new HashMap<>();
tempMap.put("name", "鄧沙利文");
tempMap.put("gender", new Random().nextInt(2) == 0 ? "男" : "女");
tempMap.put("age", new Random().nextInt(90) + 11);
tempMap.put("hobby", "活的,女的!!!");
tempMap.put("handsomeValue", "100分(滿分100分)");
tempMap.put("motto", "只所以只帥到了全亞洲,是因為其他地方審美不同!");
list.add(tempMap);
}
map.put("dataList", list);
// 生成workbook 並導出
Workbook workbook = ExcelExportUtil.exportExcel(params, map);
File savefile = new File("C:/Users/JustryDeng/Desktop/");
if (!savefile.exists()) {
boolean result = savefile.mkdirs();
System.out.println("目錄不存在,進行創建,創建" + (result ? "成功!" : "失敗!"));
}
FileOutputStream fos = new FileOutputStream("C:/Users/JustryDeng/Desktop/templateMapResult.xlsx");
workbook.write(fos);
fos.close();
}
示例四:使用模板將Object數據導出為excel示例(需要模板):
相關模型有HandsomeBoyPOJO:
/**
* 具體信息 模型
*/
public class HandsomeBoyPOJO {
/** 姓名 */
private String name;
/** 性別 */
private String gender;
/** 年齡 */
private int age;
/** 愛好 */
private String hobby;
/** 帥氣值 */
private String handsomeValue;
/** 座右銘 */
private String motto;
}
相關模型有ResultPOJO:
/**
* 采訪結果 模型
*
*/
public class ResultPOJO {
/** 標題 */
private String title;
/** 日期 */
private String date;
/** 采訪人 */
private String interviewer;
/** 信息集合 */
private List<HandsomeBoyPOJO> list;
}
導出excel的測試方法為:
/**
* 模板導出---對象組裝數據
*
* 注:實際上仍然是"模板導出---Map組裝數據",不過這里借助了工具類,將對象先轉換為了Map<String, Object>
*
* 注:.xls的模板可以導出.xls文件,也可以導出xlsx的文件;
* 同樣的, .xlsx的模板可以導出.xls文件,也可以導出xlsx的文件;
*/
@Test
public void templateExportExcelByObject() throws IOException, IllegalAccessException {
// 加載模板
TemplateExportParams params = new TemplateExportParams("templates/templateObject.xlsx");
// 組裝數據
ResultPOJO resultPOJO = new ResultPOJO();
resultPOJO.setTitle("全亞洲最帥人員名單");
resultPOJO.setInterviewer("鄧沙利文");
resultPOJO.setDate("2018-12-05");
List<HandsomeBoyPOJO> list = new ArrayList<>(8);
resultPOJO.setList(list);
HandsomeBoyPOJO handsomeBoyPOJO;
for (int i = 0; i < 5; i++) {
handsomeBoyPOJO = new HandsomeBoyPOJO();
handsomeBoyPOJO.setAge(20 + i);
handsomeBoyPOJO.setGender(i % 2 == 0 ? "女" : "男");
handsomeBoyPOJO.setHandsomeValue(95 + i + "(滿分100分)");
handsomeBoyPOJO.setHobby("女。。。。");
handsomeBoyPOJO.setMotto("我是一只小小小小鳥~");
handsomeBoyPOJO.setName("JustryDeng");
list.add(handsomeBoyPOJO);
}
// 生成workbook 並導出
Workbook workbook = ExcelExportUtil.exportExcel(params, objectToMap(resultPOJO));
File savefile = new File("C:/Users/JustryDeng/Desktop/");
if (!savefile.exists()) {
boolean result = savefile.mkdirs();
System.out.println("目錄不存在,進行創建,創建" + (result ? "成功!" : "失敗!"));
}
FileOutputStream fos = new FileOutputStream("C:/Users/JustryDeng/Desktop/templateObjectResult.xls");
workbook.write(fos);
fos.close();
}
/**
* 對象轉換為Map<String, Object>的工具類
*
* @param obj
* 要轉換的對象
*/
private static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
Map<String, Object> map = new HashMap<>(16);
Class<?> clazz = obj.getClass();
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
/*
* Returns the value of the field represented by this {@code Field}, on the
* specified object. The value is automatically wrapped in an object if it
* has a primitive type.
* 注:返回對象該該屬性的屬性值,如果該屬性的基本類型,那么自動轉換為包裝類
*/
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
運行測試函數,成功導出excel: