数据库Excel导出操作代码过于冗长惨不忍睹,无法复用。【推荐使用阿里巴巴组件:关于Easyexcel | Easy Excel】
目录
第一步:自定义注解:
第二步:实体类:
第三步:解析工具类:
第四步:使用:
依赖:
<dependency>
<groupId></groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId></groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.2</version>
</dependency>
注解配合工具类做了个小工具如下:
第一步:自定义注解:(读者请直接复制)
import ;
import ;
import ;
import ;
/**
* 自定义导出Excel数据注解
*
* @author sunziwen
* @version 1.0
* @date 2018-12-29 15:00
**/
@Retention()
@Target()
public @interface Excel {
/**
* 导出到Excel中的名字.
*/
public String name();
/**
* 日期格式, 如: yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
*/
public String readConverterExp() default "";
/**
* 导出时在excel中每个列的高度 单位为字符
*/
public double height() default 14;
/**
* 导出时在excel中每个列的宽 单位为字符
*/
public double width() default 20;
/**
* 文字后缀,如% 90 变成90%
*/
public String suffix() default "";
/**
* 当值为空时,字段的默认值
*/
public String defaultValue() default "";
/**
* 提示信息
*/
public String prompt() default "";
/**
* 设置只能选择不能输入的列内容.
*/
public String[] combo() default {};
/**
* 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
*/
public boolean isExport() default true;
}
第二步:实体类:(为每个需要的字段打上@Excel注解)
import ;
import ;
import ;
import ;
import ;
/**
* (User)表实体类
*
* @author suzniwen
* @since 2021-04-13 16:11:55
*/
@SuppressWarnings("serial")
@EqualsAndHashCode(callSuper = true)
@Data
public class User {
@Excel(name = "编号")
@ApiModelProperty(value = "主键")
private String id;
@Excel(name = "账号")
@ApiModelProperty(value = "账号")
private String loginName;
@Excel(name = "用户名")
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "用户名拼音")
private String namePinyin;
@Excel(name = "性别", readConverterExp = "1=男,0=女")
@ApiModelProperty(value = "性别")
private String gender;
@Excel(name = "证件类型",readConverterExp="1=居民身份证,2=香港居民来往内地通行证,3=澳门居民来往内地通行证,4=*居民来往大陆通行证,6=护照")
@ApiModelProperty(value = "证件类型")
private String credType;
@Excel(name = "证件号码")
@ApiModelProperty(value = "证件号码")
private String credNum;
@ApiModelProperty(value = "机构id")
private String orgId;
@Excel(name = "机构名称")
@ApiModelProperty(value = "机构名称")
private String orgName;
@Excel(name = "电话")
@ApiModelProperty(value = "电话")
private String phone;
@Excel(name = "邮箱")
@ApiModelProperty(value = "邮箱")
private String email;
@Excel(name = "人员类型",readConverterExp = "student=学生,teacher=教师,parent=家长,system=系统人员,developers=开发者,manager=管理员")
@ApiModelProperty(value = "人员类型")
private String personType;
@Excel(name = "应用系统角色编码")
@ApiModelProperty(value = "应用系统角色编码")
private String appRoleCode;
@ApiModelProperty(value = "创建时间")
private LocalDateTime createTime;
@ApiModelProperty(value = "更新时间")
private LocalDateTime updateTime;
}
第三步:解析工具类:(读者请直接复制)
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import org.;
import org.;
/**
* Excel相关操作
*
* @author sunziwen
* @version 1.0
* @date 2022-03-25 15:20
**/
public class ExcelUtil<T> {
private static final Logger log = ();
private Class<T> clazz;
public ExcelUtil(Class<T> clazz) {
= clazz;
}
/**
* 对excel表单默认第一个索引名转换成list
*
* @param input 输入流
* @return 转换后集合
*/
public List<T> importExcel(InputStream input) throws Exception {
return importExcel(, input);
}
/**
* 对excel表单指定表格索引名转换成list
*
* @param sheetName 表格索引名
* @param input 输入流
* @return 转换后集合
*/
public List<T> importExcel(String sheetName, InputStream input) throws Exception {
List<T> list = new ArrayList<T>();
Workbook workbook = (input);
Sheet sheet = null;
if ((sheetName)) {
// 如果指定sheet名,则取指定sheet中的内容.
sheet = (sheetName);
} else {
// 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = (0);
}
if (sheet == null) {
throw new IOException("文件sheet不存在");
}
int rows = ();
if (rows > 0) {
// 默认序号
// int serialNum = 0;
// 有数据时才处理 得到类的所有field.
Field[] allFields = ();
/**
* 这里是要将实体类的属性与excel表的列序号对应上,有两种方式:
* 1.按照先后顺序进行一一对应。
* 2.按照注解的name值与表头对应起来
*/
// 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
//定义一个name到Excel表的index的映射Map
HashMap<String, Integer> name2index = new HashMap<>();
//默认第一行是表头
Row r = (0);
for (int i = 0; i < ; i++) {
Cell cell = (i);
if (cell == null) {
continue;
} else {
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
(i).setCellType();
cell = (i);
String c = ();
if ((c)) {
continue;
}
(c, i);
}
}
for (int col = 0; col < ; col++) {
Field field = allFields[col];
// 将有注解的field存放到map中.
if (()) {
Excel excel = ();
String name = ();
Integer index = (name);
if (index != null) {
(true);
(index, field);
}
}
}
//下面这个是按序号一一对应的。不太友好,还是按照表头名称来对应
// for (int col = 0; col < ; col++) {
// Field field = allFields[col];
// // 将有注解的field存放到map中.
// if (()) {
// // 设置类的私有字段属性可访问.
// (true);
// (++serialNum, field);
// }
// }
for (int i = 1; i < rows; i++) {
// 从第2行开始取数据,默认第一行是表头.
Row row = (i);
int cellNum = ;
T entity = null;
for (int j = 0; j < cellNum; j++) {
Cell cell = (j);
if (cell == null) {
continue;
} else {
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
(j).setCellType();
cell = (j);
}
String c = ();
if ((c)) {
continue;
}
// 如果不存在实例则新建.
entity = (entity == null ? () : entity);
// 从map中得到对应列的field.
Field field = (j);
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = ();
if ( == fieldType) {
(entity, (c));
} else if (( == fieldType) || ( == fieldType)) {
(entity, (c));
} else if (( == fieldType) || ( == fieldType)) {
(entity, (c));
} else if (( == fieldType) || ( == fieldType)) {
(entity, (c));
} else if (( == fieldType) || ( == fieldType)) {
(entity, (c));
} else if (( == fieldType) || ( == fieldType)) {
(entity, (c));
} else if ( == fieldType) {
if ((c != null) && (() > 0)) {
(entity, ((0)));
}
} else if ( == fieldType) {
//对字符串解析成日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = ()
.replaceAll("/", "-")
.replaceAll("上午", "")
.replaceAll("下午", "")
.replaceAll(" ", " ");
("----------------------------:" + s);
Date parse = (s);
(entity, parse);
// if (() == ) {
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// ((()));
// c = (());
// } else {
// c = ();
// }
} else if ( == fieldType) {
c = ();
}
}
if (entity != null) {
(entity);
}
}
}
return list;
}
/**
* 对list数据源将其里面的数据导入到excel表单
* 针对List<Map>类型的数据
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public static void exportMapExcel(List<Map> list, String[] title, String sheetName, HttpServletResponse response) {
if (null == list || () == 0) {
return;
}
HSSFWorkbook workbook = null;
try {
// 产生工作薄对象
workbook = new HSSFWorkbook();
// excel2003中每个sheet中最多有65536行
int sheetSize = 65536;
// 取出一共有多少个sheet.
double sheetNo = (() / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
// 产生工作表对象
HSSFSheet sheet = ();
if (sheetNo == 0) {
(index, sheetName);
} else {
// 设置工作表的名称.
(index, sheetName + index);
}
HSSFRow row;
HSSFCell cell; // 产生单元格
// 产生第一行,写入标题
row = (0);
if (null == title || == 0) {
throw new RuntimeException("导出错误");
}
for (int i = 0; i < ; i++) {
cell = (i);
();
(title[i]);
}
int cell_idx = 0;
int startNo = index * sheetSize;
int endNo = (startNo + sheetSize, ());
// 写入各条记录,每条记录对应excel表中的一行
for (int i = startNo; i < endNo; i++) {
row = (i + 1 - startNo);
// 得到导出对象.
Map map = (i);
Set keySet = ();
Iterator values = ();
cell_idx = 0;
while (()) {
Object value = (());
cell = (cell_idx);
(());
cell_idx++;
}
}
}
//String filename = encodingFilename(sheetName);
("content-Type", "application/-excel");
("Content-Disposition", "attachment;filename=" + (sheetName, "UTF-8"));
// ("application/octet-stream");
// ("Content-disposition", "attachment;filename=" + (filename, "UTF-8"));
();
(());
//return filename;
} catch (Exception e) {
("导出Excel异常{}", ());
throw new RuntimeException("导出Excel失败,请联系网站管理员!");
} finally {
if (workbook != null) {
try {
();
} catch (IOException e1) {
();
}
}
}
}
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public void exportExcel(List<?> list, String sheetName, HttpServletResponse response) {
HSSFWorkbook workbook = null;
try {
// 得到所有定义字段
Field[] allFields = ();
List<Field> fields = new ArrayList<Field>();
// 得到所有field并存放到一个list中.
for (Field field : allFields) {
if (()) {
(field);
}
}
// 产生工作薄对象
workbook = new HSSFWorkbook();
// excel2003中每个sheet中最多有65536行
int sheetSize = 65536;
// 取出一共有多少个sheet.
double sheetNo = (() / sheetSize);
for (int index = 0; index <= sheetNo; index++) {
// 产生工作表对象
HSSFSheet sheet = ();
if (sheetNo == 0) {
(index, sheetName);
} else {
// 设置工作表的名称.
(index, sheetName + index);
}
HSSFRow row;
HSSFCell cell; // 产生单元格
// 产生一行
row = (0);
// 写入各个字段的列头名称
for (int i = 0; i < (); i++) {
Field field = (i);
Excel attr = ();
// 创建列
cell = (i);
// 设置列中写入内容为String类型
();
HSSFCellStyle cellStyle = ();
();
();
if (().indexOf("注:") >= 0) {
HSSFFont font = ();
(HSSFFont.COLOR_RED);
// (font);
//设置颜色
// (());
(i, 6000);
} else {
HSSFFont font = ();
// 粗体显示
(true);
// 选择需要用到的字体格式
// (font);
//设置颜色
// (.LIGHT_YELLOW.getIndex());
// 设置列宽
(i, (int) ((() + 0.72) * 256));
((short) (() * 20));
}
// (FillPatternType.SOLID_FOREGROUND);
// (true);
(cellStyle);
// 写入列名
(());
// 如果设置了提示信息则鼠标放上去提示.
if ((())) {
// 这里默认设了2-101列提示.
setHSSFPrompt(sheet, "", (), 1, 100, i, i);
}
// 如果设置了combo属性则本列只能选择不能输入
if (().length > 0) {
// 这里默认设了2-101列只能选择不能输入.
setHSSFValidation(sheet, (), 1, 100, i, i);
}
}
int startNo = index * sheetSize;
int endNo = (startNo + sheetSize, ());
// 写入各条记录,每条记录对应excel表中的一行
HSSFCellStyle cs = ();
();
();
for (int i = startNo; i < endNo; i++) {
row = (i + 1 - startNo);
// 得到导出对象.
T vo = (T) (i);
for (int j = 0; j < (); j++) {
// 获得field.
Field field = (j);
// 设置实体类私有属性可访问
(true);
Excel attr = ();
try {
// 设置行高
((short) (() * 20));
// 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
if (()) {
// 创建cell
cell = (j);
(cs);
if (vo == null) {
// 如果数据存在就填入,不存在填入空格.
("");
continue;
}
String dateFormat = ();
String readConverterExp = ();
if ((dateFormat)) {
(new SimpleDateFormat(dateFormat).format((Date) (vo)));
} else if ((readConverterExp)) {
(convertByExp(((vo)), readConverterExp));
} else {
();
// 如果数据存在就填入,不存在填入空格.
((vo) == null ? () : (vo) + ());
}
}
} catch (Exception e) {
("导出Excel失败{}", ());
}
}
}
}
//String filename = encodingFilename(sheetName);
("application/octet-stream");
("Content-disposition", "attachment;filename=" + (sheetName, "UTF-8"));
();
(());
} catch (Exception e) {
("导出Excel异常{}", ());
throw new RuntimeException("导出Excel失败,请联系网站管理员!");
} finally {
if (workbook != null) {
try {
();
} catch (IOException e1) {
();
}
}
}
}
/**
* 设置单元格上提示
*
* @param sheet 要设置的sheet.
* @param promptTitle 标题
* @param promptContent 内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
* @return 设置好的sheet.
*/
private static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle, String promptContent, int firstRow,
int endRow, int firstCol, int endCol) {
// 构造constraint对象
DVConstraint constraint = ("DD1");
// 四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation dataValidationView = new HSSFDataValidation(regions, constraint);
(promptTitle, promptContent);
(dataValidationView);
return sheet;
}
/**
* 设置某些列的值只能输入预制的数据,显示下拉框.
*
* @param sheet 要设置的sheet.
* @param textlist 下拉框显示的内容
* @param firstRow 开始行
* @param endRow 结束行
* @param firstCol 开始列
* @param endCol 结束列
* @return 设置好的sheet.
*/
private static HSSFSheet setHSSFValidation(HSSFSheet sheet, String[] textlist, int firstRow, int endRow,
int firstCol, int endCol) {
// 加载下拉列表内容
DVConstraint constraint = (textlist);
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
// 数据有效性对象
HSSFDataValidation dataValidationList = new HSSFDataValidation(regions, constraint);
(dataValidationList);
return sheet;
}
/**
* 解析导出值 0=男,1=女,2=未知
*
* @param propertyValue 参数值
* @param converterExp 翻译注解
* @return 解析后值
* @throws Exception
*/
private static String convertByExp(String propertyValue, String converterExp) throws Exception {
try {
String[] convertSource = (",");
for (String item : convertSource) {
String[] itemArray = ("=");
if (itemArray[0].equals(propertyValue)) {
return itemArray[1];
}
}
} catch (Exception e) {
throw e;
}
return propertyValue;
}
/**
* 编码文件名
*/
/*private static String encodingFilename(String filename) {
filename = ().toString() + "_" + filename + ".xls";
return filename;
}*/
}
第四步:无论导入导出,Excel表格的第一行都是跟实体类上@Excel注解的name属性进行映射对应的。
以下是示例:导出Excel表(该方法最好是返回void或者返回null),否则后台会报错(不影响运行)。
@PostMapping("/export")
@ResponseBody
public void export()
{
ExcelUtil<User> excelUtil = new ExcelUtil<>();
//要导出的数据集
List<User> list = getList();
(list, "", ());
}
附件:前端代码:
exportExcel() {
let link = ('a');
= 'none'
axios({
url: '/user/pageExport',
methods: "get",
data: {},
headers: {
token: 'eyJ0eXB1234bklkIjoie1wiZWnm7jwkJtbvdcnqo'
}
}).then((res) => {
let blob = new Blob([], {
type: "application/-excel"
}); // 2.获取请求返回的response对象中的blob 设置文件类型,这里以excel为例
let url = (blob); // 3.创建一个临时的url指向blob对象
// 4.创建url之后可以模拟对此文件对象的一系列操作,例如:预览、下载
let a = ("a");
= url;
= "导出表格.xlsx";
();
// 5.释放这个临时的对象url
(url);
})
}