一、前言

最近看见朋友写了一个导出数据库生成word文档的业务,感觉很有意思,研究了一下,这里也拿出来与大家分享一波~

先来看看生成的word文档效果吧

下面我们也来一起简单的实现吧

二、Java 导出数据库表信息生成Word文档

温馨小提示:下面只是简单的展示一些主要代码,详情可参考文末给出的案例demo源码

基本环境
  1. spring-boot 2.1.8
  2. mybatis-plus 2.2.0
  3. mysql 数据库

1、新增依赖

		<!-- ================== 将数据库表信息生成word文档信息所需 ====================== -->
<!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.lowagie/itext-rtf -->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext-rtf</artifactId>
<version>2.1.7</version>
</dependency>

2、查询表数据信息

@Mapper
public interface TableMapper { /**
* 获取指定数据库下所有表名和注释
*
* @param dbName:数据库名
* @return: java.util.List<com.zhengqing.demo.modules.system.entity.Tables>
*/
@Select("select table_name as name,table_comment as comment from information_schema.tables where table_schema =#{dbName} order by table_name")
List<Tables> getAllTables(@Param("dbName") String dbName); /**
* 获取指定表信息
*
* @param tableName:表
* @return: java.util.List<com.zhengqing.demo.modules.system.entity.TableFileds>
*/
@Select("SHOW FULL FIELDS FROM ${tableName}")
List<TableFileds> getTable(@Param("tableName") String tableName); }

3、生成word文档实现类

@Service
public class TableService implements ITableService { @Autowired
private TableMapper tableMapper;
@Autowired
private TableToWordUtil tableToWordUtil; @Override
public String getTableInfo() {
// 1、获取数据库所有表信息
List<Tables> tables = tableMapper.getAllTables(Constants.DATABASE); // 2、生成文件名信息 - 年月日时分秒
String date = null;
try {
date = DateTimeUtils.dateFormat(new Date(), DateTimeUtils.PARSE_PATTERNS[12]);
} catch (ParseException e) {
e.printStackTrace();
}
String docFileName = Constants.FILE_PATH + "\\" + Constants.FILE_NAME + "-" + date + ".doc"; // 3、调用工具类生成文件
tableToWordUtil.toWord(tables, docFileName, Constants.FILE_NAME); // 4、返回文件地址
String filePath = docFileName.replaceAll("\\\\", "/");
return filePath;
}
}

4、其中生成word文档工具类

@Service
public class TableToWordUtil { @Autowired
TableMapper tableMapper; /**
* 生成word文档
*
* @param tables:该数据库下所有表信息
* @param fileName:生成文件地址
* @param title:文件内容标题
* @return: void
*/
public void toWord(List<Tables> tables, String fileName, String title) {
Document document = new Document(PageSize.A4);
try {
// 创建文件夹
File dir = new File(Constants.FILE_PATH);
dir.mkdirs(); // 创建文件
File file = new File(fileName);
if (file.exists() && file.isFile()) {
file.delete();
}
file.createNewFile(); // 写入文件信息
RtfWriter2.getInstance(document, new FileOutputStream(fileName));
document.open();
Paragraph ph = new Paragraph();
Font f = new Font();
Paragraph p = new Paragraph(title, new Font(Font.NORMAL, 24, Font.BOLDITALIC, new Color(0, 0, 0)));
p.setAlignment(1);
document.add(p);
ph.setFont(f);
for (int i = 0; i < tables.size(); i++) {
String table_name = tables.get(i).getName();
String table_comment = tables.get(i).getComment();
List<TableFileds> fileds = tableMapper.getTable(tables.get(i).getName());
String all = "" + (i + 1) + " 表名称:" + table_name + "(" + table_comment + ")";
Table table = new Table(6); document.add(new Paragraph("")); table.setBorderWidth(1);
table.setPadding(0);
table.setSpacing(0); //添加表头的元素,并设置表头背景的颜色
Color chade = new Color(176, 196, 222); Cell cell = new Cell("编号");
addCell(table, cell, chade);
cell = new Cell("字段名");
addCell(table, cell, chade);
cell = new Cell("类型");
addCell(table, cell, chade);
cell = new Cell("是否非空");
addCell(table, cell, chade);
cell = new Cell("是否主键");
addCell(table, cell, chade);
cell = new Cell("注释");
addCell(table, cell, chade); table.endHeaders(); // 表格的主体
for (int k = 0; k < fileds.size(); k++) {
addContent(table, cell, (k + 1) + "");
addContent(table, cell, fileds.get(k).getField());
addContent(table, cell, fileds.get(k).getType());
addContent(table, cell, fileds.get(k).getNull().equals("YES") ? "否" : "是");
addContent(table, cell, fileds.get(k).getKey() != "" ? "是" : "否");
addContent(table, cell, fileds.get(k).getComment());
}
Paragraph pheae = new Paragraph(all);
//写入表说明
document.add(pheae);
//生成表格
document.add(table);
}
document.close();
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 添加表头到表格
*
* @param table
* @param cell
* @param chade
*/
private void addCell(Table table, Cell cell, Color chade) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setBackgroundColor(chade);
table.addCell(cell);
} /**
* 添加内容到表格
*
* @param table
* @param content
*/
private void addContent(Table table, Cell cell, String content) {
cell = new Cell(content);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
} }

5、其中的一些常量参数

public class Constants {

    /**
* 需要生成word文档的数据库
*/
public static final String DATABASE = "demo";
/**
* 生成文件名前缀
*/
public static final String FILE_NAME = "测试数据库"; /**
* 生成文件地址
*/
public static String FILE_PATH = "D:\\www"; }

三、测试生成效果

小编在demo中提供了一个get请求的接口http://localhost:8080/api/tableToWord

接下来我们就可以去返回的地址中查看生成文件了



案例demo源码

https://gitee.com/zhengqingya/java-workspace

Java 导出数据库表信息生成Word文档的更多相关文章

  1. PHP将数据库数据批量生成word文档

    <?php    class word{         function start(){            ob_start();            echo '<html x ...

  2. FreemarkerJavaDemo【Android将表单数据生成Word文档的方案之一(基于freemarker2.3.28,只能java生成)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这个方案只能在java中运行,无法在Android项目中运行.所以此方案是:APP将表单数据发送给后台,后台通过freemarker ...

  3. PoiDocxDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0),目前只能java生成】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 这个是<PoiDemo[Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)]>的扩展,上一篇是根 ...

  4. POI加dom4j将数据库的数据按一定格式生成word文档

    一:需求:将从数据库查处来的数据,生成word文档,并有固定的格式.(dom4j的jar包+poi的jar包) 二:解决:(1)先建立固定格式的word文档(2007版本以上),另存成为xml文件,作 ...

  5. PowerDesigner将PDM导出生成WORD文档

    PowerDesigner将PDM导出生成WORD文档 环境 PowerDesigner15 1.点击Report Temlates 制作模板 2.如果没有模板,单击New图标创建.有直接双击进入. ...

  6. PoiDemo【Android将表单数据生成Word文档的方案之二(基于Poi4.0.0)】

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 使用Poi实现android中根据模板文件生成Word文档的功能.这里的模板文件是doc文件.如果模板文件是docx文件的话,请阅读 ...

  7. java使用freemarker 生成word文档

      java 生成word文档     最近需要做一个导出word的功能, 在网上搜了下, 有用POI,JXL,iText等jar生成一个word文件然后将数据写到该文件中,API非常繁琐而且拼出来的 ...

  8. Android根据word模板文档将表单数据生成word文档的方案整理

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 前言 尝试的方案包括以下几种: freemarker 只能在java项目上运行,无法在Android项目上运行: 参考资料:<Fre ...

  9. Java Web项目中使用Freemarker生成Word文档

    Web项目中生成Word文档的操作屡见不鲜.基于Java的解决方式也是非常多的,包含使用Jacob.Apache POI.Java2Word.iText等各种方式,事实上在从Office 2003開始 ...

随机推荐

  1. 微信小程序项目-你是什么垃圾?

    垃圾分类特别火也不知道北京什么时候也开始执行,看见之前上海市民被灵魂拷问了以后垃圾真的不知道如何丢了,作为程序员就做一个小程序造福人类吧. 效果图: 一.全局的app.json和app.wxss加入了 ...

  2. http转换为https

    1.下载ssl 证数 百度ssl 证数都有 其中以便宜ssl为例子 注册登陆 选择免费版 可以使用3个月: 申请过程中需要检测该域名是否为本人所有 ,所以邮箱检测或者域名配置 很简单检测就好了: 验证 ...

  3. ng的显示与隐藏

    显示与隐藏有很多中方法,但是在ng中有自己的显示与隐藏的方法 ng-if 或者[hidden] 在此主要介绍的是[hidden] 在ng中需要摒弃dom操作的方法,使用[hidden] 使用方法: e ...

  4. 你真的懂Spring Java Config 吗?Full @Configuration vs lite @Bean mode

    Full @Configuration和lite @Bean mode 是 Spring Java Config 中两个非常有意思的概念. 先来看一下官方文档关于这两者的相关内容: The @Bean ...

  5. 智慧金融时代,大数据和AI如何为业务赋能

    前言:宜信技术人物专访是宜信技术学院推出的系列性专题,我们邀请软件研发行业的优秀技术人,分享自己在软件研发领域的实践经验和前瞻性观点. 第一期专访我们邀请到宜信科技中心AI中台负责人王东老师,从大数据 ...

  6. python+selenium遇到元素定位不到的问题,顺便记录一下自己这次的错误(报错selenium.common.exceptions.NoSuchElementException)

    今天在写selenium一个发送邮件脚本时,遇到一些没有找到页面元素的错误.经过自己反复调试,找原因百度,终于解决了.简单总结一下吧,原因有以下几点: 一:Frame控件嵌套,.Frame/Ifram ...

  7. LeetCode_933-Number of Recent Calls

    求最近3000毫秒内有多少次调用请求,每一次ping的时间一定比上一次的时间高:解法可以判断最后面一个数t1与最前一个数t2的差不大于3000毫秒,如果大于就直接舍弃,t1与t2之间的个数就是请求次数 ...

  8. iPhone 手机用 Fiddler 抓取数据包 问题

    近日公司服务升级,将所有的接口请求由HTTP升级为了HTTPS,升级后在手机中安装了Fiddler的证书,Android端抓取HTTPS请求一切正常,可是在ios端抓取HTTPS请求时一直提示“此服务 ...

  9. Vue-CLI项目vuex仓库

    0901自我总结 Vue-CLI项目vuex仓库 一.概念 vuex仓库是vue全局的数据仓库,好比一个单例,在任何组件中通过this.$store来共享这个仓库中的数据,完成跨组件间的信息交互. v ...

  10. 域渗透-Kerberos协议中spn的应用

    0x01 关于SPN 服务主体名称(SPN)是Kerberos客户端用于唯一标识给特定Kerberos目标计算机的服务实例名称. 服务主体名称是服务实例(可以理解为一个服务,比如 HTTP.MSSQL ...