共计 2133 个字符,预计需要花费 6 分钟才能阅读完成。
Foxnic-SQL (15) —— 应用记录集导入或导出 Excel
概述
很多时候,咱们须要将内部 Excel 表中的数据导入到数据库,或是须要将某个查问后果导出到 Excel 文件中,对于这种简略的操作,Foxnic-SQL 曾经内置了 ExcelReader 和 ExcelWriter 用于解决 Excel 数据。
本文中的示例代码均可在 https://gitee.com/LeeFJ/foxnic-samples 我的项目中找到。
读取 Excel 到 RcdSet
Foxnic-SQL 应用 ExcelReader 类读取 Excel 中某个 sheet 的数据,这些数据将被读取到 RcdSet,通过 RcdSet 能够实现数据库保留等操作。
在读取 Excel 前须要定义 Excel 构造,将 Excel 列映射到数据库字段,如下代码所示。一旦 Excel 数据转换成 RcdSet,开发人员就能够去做其它更多额定的数据处理。
/**
* 导入 Excel
* */
@Test
public void importExcel() throws Exception {
// 取得 DAO 对象
DAO dao = DBInstance.DEFAULT.dao();
// 取得导入的 Excel 文件
MavenProject project=new MavenProject(this.getClass());
File xlsx= FileUtil.resolveByPath(project.getSourceFile(this.getClass()).getParentFile() ,"data.xlsx");
// 构建 Excel 列 与 表字段的对应关系
ExcelStructure es=new ExcelStructure();
es.addColumn("A","id");
es.addColumn("B","name");
es.addColumn("C","price");
es.addColumn("D","create_time");
// 从第二行开始读取
es.setDataRowBegin(2);
// 读取 Excel
ExcelReader reader=new ExcelReader(xlsx);
// 读取到 RcdSet
RcdSet rs = reader.read("水果",es);
// 遍历
for (Rcd r : rs) {
// 输入数据
System.out.println(r.toJSONObject());
// 生成 Insert 语句
Insert insert=SQLBuilder.buildInsert(r,"example_goods",dao,true);
System.out.println(insert.getSQL());
// 生成 Update 语句
Update update=SQLBuilder.buildUpdate(r, SaveMode.ALL_FIELDS,"example_goods",dao);
System.out.println(update.getSQL());
}
}
写入 RcdSet 到 Excel
Foxnic-SQL 应用 ExcelWriter 类写入数据到 Excel 文件。如下代码所示,首先通过 DAO 取得 RcdSet,再通过 ExcelWriter 的 fillSheet 填充 Excel 的 Sheet 数据。
/**
* 导出 Excel
* */
@Test
public void exportExcel() {
// 取得 DAO 对象
DAO dao = DBInstance.DEFAULT.dao();
// 取得导出的 Excel 文件
MavenProject project=new MavenProject(this.getClass());
File xlsx= FileUtil.resolveByPath(project.getSourceFile(this.getClass()).getParentFile() ,"out-"+System.currentTimeMillis()+".xlsx");
// 查问数据
RcdSet rs=dao.query("select * from example_goods");
// 创立 ExcelWriter 对象
ExcelWriter writer=new ExcelWriter();
// 填充指定的 Sheet
writer.fillSheet(rs,"商品");
// 保留到文件
writer.save(xlsx);
}
小结
本节次要介绍了在 Foxni-SQL 中应用 ExcelWriter 和 ExcelReader 导出和导入 Excel 数据。Foxni-SQL 尽量为开发者提供简洁的办法实现这些操作,当然 ExcelWriter 和 ExcelReader 也具备一些高级用法以备适应简单的业务场景,这些小伙伴们可自行摸索。
相干我的项目
https://gitee.com/LeeFJ/foxnic
https://gitee.com/LeeFJ/foxnic-web
https://gitee.com/lank/eam
https://gitee.com/LeeFJ/foxnic-samples
官网文档
http://foxnicweb.com/docs/doc.html