main
黄海 2 years ago
parent 6de43fb1af
commit 5cd6c75bb7

@ -1,93 +1,27 @@
package UnitTest.ImportExcel.Bean;
import com.aspose.cells.*;
import com.dsideal.QingLong.Util.AsposeUtil;
/**
* vo
*/
public class CellBean {
private String value = "";//值
private String backgroundColor = "";//背景色
private String fontColor = "";//文字颜色
private String type="";
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getBackgroundColor() {
return backgroundColor;
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static class AsposeAddCommet {
//工作目录
public static String path = "D:\\dsWork\\QingLong\\src\\main\\resource\\Excel\\";
public static void main(String[] args) throws Exception {
//获取授权
AsposeUtil.getLicense();
// 打开现有的工作簿
Workbook workbook = new Workbook(path + "\\1.xlsx");
Worksheet sheet = workbook.getWorksheets().get(0);
//添加新的批注
CommentCollection comments = sheet.getComments();
comments.clear();
* vo
*/
public class CellBean {
private String value = "";//值
private String backgroundColor = "";//背景色
public String getValue() {
return value;
}
int idx = comments.add(7, 3);
Comment comment = comments.get(idx);
//System.out.println(comment.getCommentShape().getFill());
comment.setNote("我是内容");
comment.setAuthor("黄海");
comment.getFont().setName("黑体");
// 设置批注的背景颜色为黄色
// 保存工作簿
workbook.save(path + "\\4.xlsx");
}
public void setValue(String value) {
this.value = value;
}
public static class AsposeAddXiaLaKuang {
//工作目录
public static String path = "D:\\dsWork\\QingLong\\src\\main\\resource\\Excel\\";
public String getBackgroundColor() {
return backgroundColor;
}
public static void main(String[] args) throws Exception {
//获取授权
AsposeUtil.getLicense();
// 打开现有的工作簿
Workbook workbook = new Workbook(path+"\\1.xlsx");
// 获取第一个工作表
Worksheet worksheet = workbook.getWorksheets().get(0);
// 创建下拉列表
Validation validation = worksheet.getValidations().get(worksheet.getValidations().add());
validation.setType(ValidationType.LIST);
validation.setFormula1("男,女,未知"); // 设置下拉列表的选项
// 设置下拉列表的范围
CellArea area = new CellArea();
area.StartRow = 1; // 从第2行开始
area.EndRow = 29; // 到第30行结束
area.StartColumn = 0; // 第一列
validation.addArea(area);
// 应用到工作表
worksheet.getValidations().add(validation);
// 保存工作簿
workbook.save(path+"\\3.xlsx");
}
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
}

@ -1,80 +0,0 @@
package UnitTest.ImportExcel;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import com.aspose.cells.Workbook;
import com.dsideal.QingLong.Util.AsposeUtil;
import com.dsideal.QingLong.Util.ExcelUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.hikaricp.HikariCpPlugin;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static String path = "D:\\dsWork\\QingLong\\src\\main\\resource\\Excel\\";
public static void main(String[] args) throws Exception {
//加载License
AsposeUtil.getLicense();
//告之配置文件位置
PropKit.use("application.properties");
HikariCpPlugin hp = new HikariCpPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"),
PropKit.get("password").trim(), PropKit.get("driverClassName"));
hp.start();
// 配置ActiveRecord插件
ActiveRecordPlugin arp = new ActiveRecordPlugin(hp);
//配置默认小写
arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
arp.setDialect(new PostgreSqlDialect());
arp.start();
//源文件
String source = path + "\\source.xlsx";
Workbook workbook = new Workbook(source);
//1、共有几个Sheet表
int sheetCount = workbook.getWorksheets().getCount();
//2、读取每张表的表信息
String[] tableNames = {"ds_source_1", "ds_source_2", "ds_source_3", "ds_source_4", "ds_source_5", "ds_source_6", "ds_source_7"};
if (sheetCount != tableNames.length) {
System.out.println("上传的EXCEL中 Sheet表数量为" + sheetCount + "个,但给定的名称数量共" + tableNames.length + "个,两者不匹配,程序无法继续!");
return;
}
//表名研发人员在界面上录入程序需要检查此表名是不是存在如果存在返回错误信息不存在则可以生成创建表的SQL语句
InputStream is = new FileInputStream(source);
XSSFWorkbook wb = new XSSFWorkbook(is);
for (int i = 0; i < sheetCount; i++) {
String tableName = tableNames[i];
//开发时暴力删除掉原表,在正式上线前要注意:不能简单粗暴的删除!!
ExcelUtil.dropTable(tableName);
//判断表是不是已存在
if (ExcelUtil.isTableExist(tableName)) {
System.out.println("表" + tableName + "已存在,不能删除,程序无法继续!");
return;
}
try {
Kv kv = ExcelUtil.getTableStructInfo(wb, i);
if (!kv.getBoolean("success")) {
System.out.println(kv.getStr("message"));
return;
}
ExcelUtil.createTable(tableName, kv);
} catch (Exception err) {
System.out.println("“" + wb.getSheetName(i) + "”表配置错误,请检查后重新上传!");
System.out.println(err);
wb.close();
return;
}
}
wb.close();
}
}

@ -0,0 +1,113 @@
package UnitTest.ImportExcel;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.aspose.cells.Workbook;
import com.dsideal.QingLong.Util.AsposeUtil;
import com.dsideal.QingLong.Util.GenericTemplateUtil;
import com.jfinal.kit.Kv;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.hikaricp.HikariCpPlugin;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestAll {
public static String path = "D:\\dsWork\\QingLong\\src\\main\\resource\\Excel\\";
//模拟上传文件的文件名称
public static String upload_excel_filename = "b61a2af2-223f-4058-a675-b212e4dd9487" + ".xlsx";
/**
*
*
* @param toDoKvList
* @return
*/
public static void change(List<Kv> toDoKvList) {
int cnt = 0;
for (Kv kv : toDoKvList) {
List<Record> _list = (List<Record>) kv.get("list");
for (Record record : _list) {
record.set("column_type", "varchar(2048)");
record.set("allow_blank", false);
}
cnt++;
kv.set("table_name", "ds_source_" + cnt);
}
}
public static void main(String[] args) throws Exception {
//加载License
AsposeUtil.getLicense();
//告之配置文件位置
PropKit.use("application.properties");
HikariCpPlugin hp = new HikariCpPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"),
PropKit.get("password").trim(), PropKit.get("driverClassName"));
hp.start();
// 配置ActiveRecord插件
ActiveRecordPlugin arp = new ActiveRecordPlugin(hp);
//配置默认小写
arp.setContainerFactory(new CaseInsensitiveContainerFactory(true));
arp.setDialect(new PostgreSqlDialect());
arp.start();
//源文件
String source = path + "\\"+ upload_excel_filename;
Workbook workbook = new Workbook(source);
//共有几个Sheet表
int sheetCount = workbook.getWorksheets().getCount();
//解析上传EXCEL中的每个Sheet解析出表头信息表名描述等信息
InputStream is = new FileInputStream(source);
XSSFWorkbook wb = new XSSFWorkbook(is);
List<Kv> kvList = new ArrayList<>();
for (int i = 0; i < sheetCount; i++) {
try {
Kv kv = GenericTemplateUtil.getTableStruct(wb, i);
if (!kv.getBoolean("success")) {
System.out.println(kv.getStr("message"));
return;
}
kvList.add(kv);
} catch (Exception err) {
System.out.println("“" + wb.getSheetName(i) + "”表配置错误,请检查后重新上传!");
System.out.println(err);
wb.close();
return;
}
}
//提供给前台进行修改属性(现在这里是模拟的前端处理后的代码)
// (1)整体上需要添加一个参数table_name
// (2)list中每个 Record 添加属性column_typeallow_blank,在JAVA中函数的参数是一个List<Kv>时,是按参数引用的,所以,直接修改即可
change(kvList);
//开发时暴力删除掉原表,在正式上线前要注意:不能简单粗暴的删除!!
for (Kv kv : kvList) {
String tableName = kv.getStr("table_name");
GenericTemplateUtil.dropTable(tableName);
}
//判断表是不是已存在
for (Kv kv : kvList) {
String tableName = kv.getStr("table_name");
if (GenericTemplateUtil.isTableExist(tableName)) {
System.out.println("表" + tableName + "已存在,不能删除,程序无法继续!");
return;
}
}
//检查通过,处理建表逻辑
for (Kv kv : kvList) {
String tableName = kv.getStr("table_name");
GenericTemplateUtil.createTable(tableName, kv, upload_excel_filename);//创建表
}
System.out.println("恭喜,所有的表格创建成功!");
wb.close();
}
}

@ -1,6 +1,5 @@
package UnitTest.ImportExcel;
import com.dsideal.QingLong.Util.ExcelUtil;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.CaseInsensitiveContainerFactory;

@ -5,10 +5,7 @@ import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import org.apache.poi.ss.formula.eval.ErrorEval;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@ -16,12 +13,11 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtil {
public class GenericTemplateUtil {
/**
*
*
@ -35,18 +31,6 @@ public class ExcelUtil {
return output;
}
/**
*
*
* @param input
* @return
*/
public static String removeNumbers(String input) {
String regex = "\\d+"; // 匹配数字的正则表达式
String result = input.replaceAll(regex, ""); // 使用replaceAll方法将匹配到的数字替换为空字符串
return result;
}
/**
* )
* vo
@ -57,54 +41,6 @@ public class ExcelUtil {
private static CellBean getCellBean(Cell cell) {
CellBean dto = new CellBean();//创建单元格对象
if (cell != null) {
//值
switch (cell.getCellType()) {
case NUMERIC://导入数据,没有支持到时间的,一般都是到日期为止
if (DateUtil.isCellDateFormatted(cell)) {
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", LocaleUtil.getUserLocale());
sdf.setTimeZone(LocaleUtil.getUserTimeZone());
dto.setValue(sdf.format(cell.getDateCellValue()));
dto.setType("date");
} else {
String type;
Long longVal = Math.round(cell.getNumericCellValue());
Double doubleVal = cell.getNumericCellValue();
if (Double.parseDouble(longVal + ".0") == doubleVal) { //判断是否含有小数位.0
type = "int";
} else {
type = "float8";
}
DataFormatter formatter = new DataFormatter();
dto.setValue(formatter.formatCellValue(cell));
dto.setType(type);
}
break;
case STRING:
dto.setValue(cell.getStringCellValue());
dto.setType("varchar(1024)");
break;
case BOOLEAN:
dto.setValue(String.valueOf(cell.getBooleanCellValue()));
dto.setType("bool");
break;
case FORMULA:
dto.setValue(cell.getCellFormula());
dto.setType("varchar(1024)");
break;
case BLANK:
dto.setValue("");
dto.setType("varchar(1024)");
break;
case ERROR:
dto.setValue(ErrorEval.getText(cell.getErrorCellValue()));
dto.setType("varchar(1024)");
break;
default: {
dto.setValue("Unknown Cell Type: " + cell.getCellType());
dto.setType("varchar(1024)");
}
}
// xlsx 07版
//背景颜色
CellStyle cellStyle = cell.getCellStyle();
XSSFColor xssfColor = (XSSFColor) cellStyle.getFillForegroundColorColor();
@ -124,7 +60,7 @@ public class ExcelUtil {
* @return
*/
public static List<Integer> getHead(XSSFSheet sheet) {
List<Integer> _list = new ArrayList<>();
List<Integer> list = new ArrayList<>();
//整行都是同一种非空白颜色,视为表头
// 遍历行
for (int i = 0; i <= sheet.getLastRowNum(); i++) {
@ -138,45 +74,17 @@ public class ExcelUtil {
Cell cell = row.getCell(j);
if (cell == null) continue;
CellBean eo = getCellBean(cell);
//记录背景颜色数量
if (_map.containsKey(eo.getBackgroundColor()))
_map.put(eo.getBackgroundColor(), _map.get(eo.getBackgroundColor()) + 1);
else
_map.put(eo.getBackgroundColor(), 1);
}
if (_map.size() == 1 && _map.entrySet().iterator().next().getKey().startsWith("#")) {
_list.add(i + 1);
list.add(i + 1);
}
}
}
return _list;
}
/**
*
*
* @param sheet
* @param st
* @param ed
* @return
*/
public static List<List<String>> getStruct(XSSFSheet sheet, int st, int ed) {
List<List<String>> list = new ArrayList<>();
// 遍历行
for (int i = st; i <= ed; i++) {
//获得行
Row row = sheet.getRow(i);
List<String> r = new ArrayList<>();
//遍历列
if (row != null) {
for (int j = 0; j < row.getLastCellNum(); j++) {
Cell cell = row.getCell(j);
if (cell == null) continue;
CellBean eo = getCellBean(cell);
r.add(eo.getType());
}
}
list.add(r);
}
return list;
}
@ -235,16 +143,18 @@ public class ExcelUtil {
/**
*
*/
public static Kv getTableStructInfo(XSSFWorkbook wb, int sheetIdx) {
public static Kv getTableStruct(XSSFWorkbook wb, int sheetIdx) {
Kv kv = Kv.create();
//读取sheet页
XSSFSheet sheet = wb.getSheetAt(sheetIdx);
//找到表头
List<Integer> _list = getHead(sheet);
//表名称
String sheetName = wb.getSheetName(sheetIdx);
//只允许1行或2行
if (_list.size() == 0 || _list.size() > 2) {
kv.set("success", false);
kv.set("message", "表 “" + wb.getSheetName(sheetIdx) + "” 没有正确设置表头背景色,要求表头可以为一行或两行,而且必须背景色是同一种非空白颜色!");
kv.set("message", "表 “" + sheetName + "” 没有正确设置表头背景色,要求表头可以为一行或两行,而且必须背景色是同一种非空白颜色!");
return kv;
}
// 标题,定义为表头上面的部分
@ -275,10 +185,11 @@ public class ExcelUtil {
}
}
kv.set("success", true);
kv.set("message", "信息获取成功!");
kv.set("message", "表结构获取成功!");
kv.set("list", list);
kv.set("data_start_row", ed.getRowNum() + 1);//真实数据的起始行索引
kv.set("column_num", ed.getLastCellNum());//一共多少列
kv.set("sheet_name", sheetName);
return kv;
}
@ -289,9 +200,9 @@ public class ExcelUtil {
* @param input
* @return
*/
public static Kv createTable(String tableName, Kv input) {
public static Kv createTable(String tableName, Kv input, String upload_excel_filename) {
List<Record> list = (List<Record>) input.get("list");
String sheetName = input.getStr("sheet_name");
String colSql = "", commentSql = "";
for (Record record : list) {
String column_name = record.getStr("column_name");
@ -309,35 +220,26 @@ public class ExcelUtil {
finalSql += "COMMENT ON COLUMN \"public\".\"" + tableName + "\".\"id\" IS '主键自增长ID';\n";
finalSql += commentSql;
finalSql += "COMMENT ON TABLE \"public\".\"" + tableName + "\" IS '" + sheetName + "';";
Db.update(finalSql);
//写入模板与表结构的关系t_importexcel_mapping
String sql = "delete from t_importexcel_mapping where table_name=?";
Db.update(sql, tableName);
List<Record> writeList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
Record record = new Record();
record.set("table_name", tableName);
record.set("column_name", record.getStr("column_name"));
record.set("column_name", list.get(i).getStr("column_name"));
record.set("excel_column_idx", i + 1);
record.set("memo", record.getStr("memo"));
record.set("column_type", record.getStr("column_type"));
list.add(record);
record.set("memo", list.get(i).getStr("memo"));
record.set("column_type", list.get(i).getStr("column_type"));
record.set("upload_excel_filename", upload_excel_filename);
writeList.add(record);
}
Db.batchSave("t_importexcel_mapping", writeList, 100);
//写入t_importexcel_config
sql = "delete from t_importexcel_config where table_name=?";
Db.update(sql, tableName);
Record record = new Record();
record.set("table_name", tableName);
record.set("excel_module_filename", "先不写上去");
record.set("data_start_row", input.getInt("data_start_row"));
record.set("column_num", input.getInt("column_num"));
Db.save("t_importexcel_config", "table_name", record);
Kv kv = Kv.create();
kv.set("success", true);
kv.set("message", "表结构创建成功!");
@ -419,8 +321,4 @@ public class ExcelUtil {
//关闭excel
wb.close();
}
public static void main(String[] args) {
System.out.println(removeKuoHao("现状_配置如交互式白板标明尺寸OPS计算机标明处理器/内存/硬盘等)"));
}
}
Loading…
Cancel
Save