文章目录
- 1、查询某张表字段信息
- 2、TableVo接收sql查询得到的数据
- 3、excel导出
- 4、导出案例
1、查询某张表字段信息
select column_name as columnName, -- 字段名
COLUMN_DEFAULT as colDefault, -- 默认值
column_key as columnKey, -- PRI-主键,UNI-唯一键,MUL-外键
column_comment as columnComment, -- 字段中文名称
column_type as columnType, -- 字段类型
IS_NULLABLE as isNullLable -- 是否允许为空
from information_schema.columns where table_schema = (select database()) and table_name = ('sys_role_dept') order by ordinal_position
2、TableVo接收sql查询得到的数据
package com.dtt.web.domain.vo;
import lombok.Data;
@Data
public class TableVo {
public String columnName; // 字段名
public String colDefault; // 默认值
public String columnKey; // PRI-主键,UNI-唯一键,MUL-外键
public String columnComment; // 字段中文名称
public String columnType; // 字段类型
public String isNullLable; // 是否为空 YES,NO
}
3、excel导出
注意:需要hutool依赖
@Test
public void exportTable(){
String tableName = "ssa_store_info";
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
List<TableVo> sysRoleDept = demoMapper.getList(tableName);
List<Map<String, Object>> rows = sysRoleDept.stream().map(
a -> {
Map<String, Object> row = new LinkedHashMap<>();
String PRI = "N"; // 主键
String MUL = "N"; // 外键
String UNI = "N"; // 唯一
String defaultStr = "N";
String isNotNull = "N"; // 是否非空
if (a.getIsNullLable().equals("NO")) isNotNull = "Y";
if (Strings.isNotBlank(a.getColDefault())) defaultStr = a.getColDefault();
String columnKey = a.getColumnKey();
if (columnKey.equals("PRI")) {
PRI = "Y";
UNI = "Y";
}
if (columnKey.equals("MUL")) MUL = "Y";
if (columnKey.equals("UNI")) UNI = "Y";
row.put("字段中文名", a.getColumnComment());
row.put("字段名", a.getColumnName());
row.put("数据类型", a.getColumnType());
row.put("主键", PRI);
row.put("外键", MUL);
row.put("唯一", UNI);
row.put("非空", isNotNull);
row.put("缺省", defaultStr);
row.put("描述", a.getColumnComment());
return row;
}
).collect(Collectors.toList());
ExcelWriter writer = ExcelUtil.getWriter("e:/"+tableName+sdf.format(new Date())+".xlsx");
// 微调一下每个列的宽度
writer.setColumnWidth(0,16);
writer.setColumnWidth(1,16);
writer.setColumnWidth(2,16);
writer.setColumnWidth(3,16);
writer.setColumnWidth(4,16);
writer.setColumnWidth(5,16);
writer.setColumnWidth(6,16);
writer.setColumnWidth(7,16);
writer.setColumnWidth(8,16);
//一次性写出内容,强制输出标题
writer.write(rows, true);
//关闭writer,释放内存
writer.close();
System.out.println();
}