Foxnic-SQL (15) —— 使用记录集导入或导出Excel

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容