0、引入包:
compile 'com.alibaba:easyexcel:2.2.6'
1、通过模板生成xlsx文件:
定义模板:
组装map的列表数据:
JSONArray arrays = new JSONArray(ret);
for (int i = 0; i < arrays.length(); i++) {
JSONObject json = (JSONObject) arrays.get(i);
String id = json.getString("id");
String name = json.getString("name");
json = json.getJSONObject("extraData");
long folder_used = json.getLong("folder_used");
long folder_capacity = json.getLong("folder_capacity");
Map<String,Object> map = new HashMap<String, Object>();
map.put("id", id);
map.put("name", name);
map.put("folder_used", folder_used);
map.put("folder_capacity", folder_capacity);
map.put("used_prcent", decimalFormat.format(folder_used/folder_capacity));
map.put("folder_used_G", decimalFormat.format(folder_used/1024/1024/1024));
map.put("folder_capacity_G", decimalFormat.format(folder_capacity/1024/1024/1024));
datas.add(map);
datas.add(map);
}
String templateFileName = "template.xlsx";
String fileName = System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(datas);
关键代码只有一行:
EasyExcel.write(fileName).withTemplate(templateFileName).sheet().doFill(datas);
2、无模板,直接写文件
定义model类:
import com.alibaba.excel.annotation.ExcelProperty;
public class ExportData {
@ExcelProperty("ID")
private String id;
@ExcelProperty("名称")
private String name;
@ExcelProperty("类型")
private String idType;
@ExcelProperty("总空间")
private float capacity;
@ExcelProperty("已用空间")
private float used;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public float getCapacity() {
return capacity;
}
public void setCapacity(float capacity) {
this.capacity = capacity;
}
public float getUsed() {
return used;
}
public void setUsed(float used) {
this.used = used;
}
}
组装list,填入
List<ExportData> datas = getData()
String fileName = System.currentTimeMillis() + ".xlsx";
EasyExcel.write(fileName, ExportData.class).sheet("模板").doWrite(datas);
组装多个,生成多个sheet
public static void export(String fileName,List<List<ExportData>> datas,List<String> sheetNames) {
ExcelWriter excelWriter = null;
try {
// 这里 指定文件
excelWriter = EasyExcel.write(fileName).build();
for (int i = 0; i < datas.size(); i++) {
// 每次都要创建writeSheet 这里注意必须指定sheetNo 而且sheetName必须不一样。
// 可以每次都变,我这里为了方便 所以用的同一个class 实际上可以一直变
WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetNames.get(i)).head(ExportData.class).build();
List<ExportData> dataList = datas.get(i);
excelWriter.write(dataList, writeSheet);
}
} finally {
// 千万别忘记finish 会帮忙关闭流
if (excelWriter != null) {
excelWriter.finish();
}
}
}