当前位置:网站首页>实体List转为excel
实体List转为excel
2022-08-08 08:28:00 【[email protected】
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
package com.mabo.excel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellStyle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class CreateTest<T> {
public static<T> File create(Class<T> aClass, List<T> list, String fileName) throws IOException {
// 创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet("sheet1");
// 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow(0);
// 添加标题行
HSSFCell cell = null;
Field[] fields = aClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
// 获取行内对应单元格
cell = row.createCell(i);
// 单元格赋值
cell.setCellValue(fields[i].getName());
}
// 写入实体数据,实际应用中这些数据从数据库得到,list中字符串的顺序必须和数组strArray中的顺序一致
int i = 0;
for (int j = 0; j < list.size(); j++) {
T t = list.get(i);
i++;
row = sheet.createRow(i );
// 添加数据行
//数据转为Json
String json= JSON.toJSONString(t);//关键
JSONObject parse = (JSONObject) JSONObject.parse(json);
for (int z = 0; z < fields.length; z++) {
Field field=fields[z];
cell = row.createCell(z);
// 获取行内对应单元格
String name = field.getName();
Object o = parse.get(name);
// 单元格赋值
if (o instanceof Long){
long o1 = (long) o;
Date date = new Date();
date.setTime(o1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(simpleDateFormat.format(date));
}
else if (o instanceof String){
cell.setCellValue((String) o);
}
else if (o instanceof Double){
cell.setCellValue((double) o);
}
else if (o instanceof Boolean){
cell.setCellValue((boolean) o);
}
}
}
// // 第六步,将文件存到指定位置
FileOutputStream fout = new FileOutputStream(fileName);
try {
wb.write(fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
finally {
fout.close();
}
return new File(fileName);
}
}
原网站
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_47053123/article/details/126197277
边栏推荐
猜你喜欢
随机推荐
【vulhub】PostGresql高权限命令执行漏洞复现(CVE-2019-9193)
蔚来杯2022牛客暑期多校训练营6 ABGJM
分清成员函数非成员函数和友元函数
Kotlin协程:生命周期原理
under项目under项目
文件包含漏洞-知识点
The industry's first "Causal Inference Whole Process" Challenge!WAIC 2022 · Hackathon invites global developer elites to challenge
双馈风电机组备用容量控制策略研究
HyperLynx(三)传输线类型及相关设置
关于#sql#的问题:kingwow数据库
C#实现在企业微信内发送消息给指定人员帮助类
js中call、bind、apply的区别?
【优化调度】基于粒子群实现并网模型下微电网的经济调度优化附matlab代码
大文件上传时如何做到 秒传?
用平衡二叉搜索树解决硬木种类问题
推荐系统 使用surprise库基于协同过滤的方法实现
攻防世界——fakebook
Implementation principle of priority queue
百度飞浆EISeg高效交互式标注分割软件的使用教程
生成密码字典的方法