一、前言
最近看見朋友寫了一個導出資料庫生成word文檔的業務,感覺很有意思,研究了一下,這裡也拿出來與大家分享一波~
先來看看生成的word文檔效果吧
下面我們也來一起簡單的實作吧
二、Java 導出資料庫表資訊生成Word文檔
溫馨小提示:下面隻是簡單的展示一些主要代碼,詳情可參考文末給出的案例demo源碼
基本環境
- spring-boot 2.1.8
- mybatis-plus 2.2.0
- mysql 資料庫
1、新增依賴
com.lowagie
itext
2.1.7
com.itextpdf
itext-asian
5.2.0
com.lowagie
itext-rtf
2.1.7
2、查詢表資料資訊
@Mapper
public interface TableMapper {
@Select("select table_name as name,table_comment as comment from information_schema.tables where table_schema =#{dbName} order by table_name")
List getAllTables(@Param("dbName") String dbName);
@Select("SHOW FULL FIELDS FROM ${tableName}")
List 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 = 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(