一、前言
最近看見朋友寫了一個導出數據庫生成word文檔的業務,感覺很有意思,研究了一下,這里也拿出來與大家分享一波~
先來看看生成的word文檔效果吧
下面我們也來一起簡單的實現吧
二、Java 導出數據庫表信息生成Word文檔
溫馨小提示:下面只是簡單的展示一些主要代碼,詳情可參考文末給出的案例demo源碼
基本環境
- spring-boot 2.1.8
- mybatis-plus 2.2.0
- 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
接下來我們就可以去返回的地址中查看生成文件了