Java查詢數據庫表信息導出Word

參考:?POI生成Word多級標題格式_poi設置word標題-CSDN博客

1.概述

? ? ? ? 使用jdbc查詢數據庫把表信息導出為word文檔, 導出為word時需要下載word模板文件。

已實現數據庫:?

  • KingbaseES, 實現代碼: 點擊跳轉

2.效果圖

2.1.生成word內容

所有數據庫合并

數據庫不合并

2.2.生成文件列表

3.代碼文件結構

4.代碼實現

4.1.dto

4.1.1.DbInfoDTO.java

package cn.nordrassil.db2doc.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;@Data
@AllArgsConstructor
@NoArgsConstructor
public class DbInfoDTO {private String dbName;private String dbDescribe;private List<TableInfo> tableInfos;@Data@AllArgsConstructor@NoArgsConstructorpublic static class TableInfo {private String tableName;private String tableDescribe;private List<TableField> tableFields;private List<List<String>> tableContents;public TableInfo(String tableName, String tableDescribe, List<TableField> tableFields) {this.tableName = tableName;this.tableDescribe = tableDescribe;this.tableFields = tableFields;}}@Data@AllArgsConstructor@NoArgsConstructorpublic static class TableField {private String name;private String type;private Integer length;private String allowEmpty;private String isPrimaryKey;private String defaultValue;private String describe;}}

4.1.2.DbConnParamDTO.java

package cn.nordrassil.db2doc.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@AllArgsConstructor
@NoArgsConstructor
public class DbConnParamDTO {private String host;private Integer port;private String username;private String password;// 隨機填一個數據庫即可private String randomDatabase;// 數據庫前綴過濾private String dbPrefixFilter;// 等于true是只會導出第一張表private Boolean testRun;
}

4.1.3.ExportWordParamDTO

package cn.nordrassil.db2doc.dto;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.util.List;@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExportWordParamDTO {// 數據信息private List<DbInfoDTO> ds;// 導出word模板文件private String wordTemplateFile;// 導出目錄private String exportFolder;// 所有數據庫是否合并到一個文檔, 默認每個數據庫一個文檔private Boolean merge = Boolean.FALSE;
}

4.2.util

4.2.1.CommonUtil.java

package cn.nordrassil.db2doc.util;import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;public class CommonUtil {private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");private static DateTimeFormatter dateFormatter2 = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");public static String readByLineRs(String path) {StringBuffer sb = new StringBuffer();File file = new File(path);BufferedReader reader = null;String temp = null;try {reader = new BufferedReader(new FileReader(file));while ((temp = reader.readLine()) != null) {sb.append(temp).append("\n");}} catch (Exception e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (Exception e) {e.printStackTrace();}}}return sb.toString();}/*** 依次替換{}* 例 : join("a={},b={}",1,2) => a=1,b=2** @param str* @param param* @return*/public static String join(String str, Object... param) {try {for (Object p : param) {String processedParam = p.toString().replace("\\", "\\\\");str = str.replaceFirst("\\{\\}", processedParam);}} catch (Exception e) {for (Object p : param) {str = str + p;}}return str;}public static void writeString(String content, String path) {try {File file = new File(path);if (!file.exists()) {file.createNewFile();}FileWriter fw = new FileWriter(file.getAbsoluteFile());BufferedWriter bw = new BufferedWriter(fw);bw.write(content);bw.close();} catch (IOException e) {e.printStackTrace();}}public static void info(String str, Object... param) {System.out.println(LocalDateTime.now().format(dateFormatter) + "|" + join(str, param));}public static String getDayTime() {return LocalDateTime.now().format(dateFormatter2);}public static void createDirectoryIfNotExists(String absolutePath) {File file = new File(absolutePath);// 獲取文件所在的目錄File parentDir = file.getParentFile();if (parentDir != null && !parentDir.exists()) {// 創建目錄parentDir.mkdirs();}}}

4.3.service

4.3.1.DbInfoExportWordService.java

package cn.nordrassil.db2doc;import cn.nordrassil.db2doc.dto.DbInfoDTO;
import cn.nordrassil.db2doc.dto.ExportWordParamDTO;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTShd;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyles;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import static cn.nordrassil.db2doc.util.CommonUtil.*;// 參考: https://blog.csdn.net/qq_37945565/article/details/121518330public class DbInfoExportWordService {public static List<String> tableTitles = new ArrayList<String>() {{add("序號");add("字段名");add("字段類型");add("長度");add("非空");add("主鍵");add("默認值");add("注釋");}};public static List<String> fields = new ArrayList<String>() {{add("name");add("type");add("length");add("allowEmpty");add("isPrimaryKey");add("defaultValue");add("describe");}};public static void generateWord(ExportWordParamDTO paramDTO) throws Exception {// 獲得模板文檔的整體樣式XWPFDocument template = new XWPFDocument(new FileInputStream(paramDTO.getWordTemplateFile()));CTStyles wordStyles = template.getStyle();int totalTableCount = 0;int index = 1;List<DbInfoDTO> ds = paramDTO.getDs();XWPFDocument document = null;boolean merge = paramDTO.getMerge() != null && paramDTO.getMerge();if (merge) {document = new XWPFDocument();}for (DbInfoDTO d : ds) {info("執行第[{}/{}]生成word文檔...表數量:{}", index, ds.size(), d.getTableInfos().size());if (!merge) {document = new XWPFDocument();}// 獲取新建文檔對象的樣式XWPFStyles newStyles = document.createStyles();// 關鍵行// 修改設置文檔樣式為靜態塊中讀取到的樣式newStyles.setStyles(wordStyles);if (merge) {XWPFParagraph title1 = document.createParagraph();title1.setStyle("2");XWPFRun titleRun1 = title1.createRun();String dbText = index + "." + d.getDbName();if (d.getDbDescribe() != null) {dbText += "(" + d.getDbDescribe().replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "") + ")";}titleRun1.setText(dbText);}List<DbInfoDTO.TableInfo> tableInfos = d.getTableInfos();totalTableCount += tableInfos.size();for (int k = 0; k < tableInfos.size(); k++) {DbInfoDTO.TableInfo tableInfo = tableInfos.get(k);XWPFParagraph title2 = document.createParagraph();XWPFRun titleRun2 = title2.createRun();String tableText;if (merge) {title2.setStyle("3");tableText = index + "." + (k + 1) + "." + tableInfo.getTableName();} else {title2.setStyle("2");tableText = (k + 1) + "." + tableInfo.getTableName();}if (tableInfo.getTableDescribe() != null) {tableText += "(" + tableInfo.getTableDescribe().replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "") + ")";}titleRun2.setText(tableText);// 創建表格(第一列為序號)List<DbInfoDTO.TableField> tableFields = tableInfo.getTableFields();XWPFTable table = document.createTable(tableFields.size(), 8);int titleFontSize = 10;int textFontSize = 8;// 設置表格標題樣式for (int i = 0; i < table.getRows().get(0).getTableCells().size(); i++) {XWPFTableCell cell = table.getRows().get(0).getCell(i);XWPFParagraph cellParagraph = cell.getParagraphs().get(0);cellParagraph.setIndentationLeft(0); // 設置左側縮進為0cellParagraph.setIndentationRight(0); // 設置右側縮進為0cellParagraph.setIndentationFirstLine(0); // 設置首行縮進為0cellParagraph.setIndentationLeft(0);// 設置單元格背景色為灰色CTTcPr cellPr = cell.getCTTc().addNewTcPr();CTShd shd = cellPr.addNewShd();shd.setFill("D3D3D3");cellParagraph.setAlignment(ParagraphAlignment.CENTER);XWPFRun cellRun = cellParagraph.createRun();cellRun.setBold(true);cellRun.setText(tableTitles.get(i));cellRun.setFontSize(titleFontSize);}// 寫入表格內容for (int row = 1; row < table.getNumberOfRows(); row++) {for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {XWPFTableCell cell = table.getRow(row).getCell(col);XWPFParagraph cellParagraph = cell.getParagraphs().get(0);XWPFRun cellRun = cellParagraph.createRun();if (col == 0) {cellRun.setText(row + "");} else {DbInfoDTO.TableField tableField = tableFields.get(row - 1);JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(tableField));cellRun.setText(jsonObject.getString(fields.get(col - 1)));}CTTcPr tcPr = cell.getCTTc().getTcPr();if (tcPr == null) {tcPr = cell.getCTTc().addNewTcPr();}if (!tcPr.isSetTcMar()) {tcPr.addNewTcMar();}tcPr.getTcMar().addNewLeft().setW(0);tcPr.getTcMar().addNewRight().setW(0);tcPr.getTcMar().addNewTop().setW(0);tcPr.getTcMar().addNewBottom().setW(0);cellRun.setFontSize(textFontSize);cellParagraph.setIndentationLeft(0);// 設置段落左對齊cellParagraph.setAlignment(ParagraphAlignment.LEFT);// 設置左縮進為 0cellParagraph.setIndentationLeft(0);}}}if (!merge) {// 保存文檔String outputFile = paramDTO.getExportFolder() + File.separator + d.getDbName() + ".docx";createDirectoryIfNotExists(outputFile);try (FileOutputStream out = new FileOutputStream(outputFile)) {document.write(out);info("第[{}/{}]數據庫信息生成word文檔完成, 文檔路徑:{}", index, ds.size(), outputFile);} catch (IOException e) {e.printStackTrace();}}index++;}if (merge) {// 保存文檔String outputFile = paramDTO.getExportFolder() + File.separator + getDayTime() + "_all_db.docx";createDirectoryIfNotExists(outputFile);try (FileOutputStream out = new FileOutputStream(outputFile)) {document.write(out);info("所有數據庫信息生成word文檔完成, 文檔路徑:{}", outputFile);} catch (IOException e) {e.printStackTrace();}}info("數據庫已導出為word文檔完成, 數據庫數量:{}, 所有表總數量:{}", ds.size(), totalTableCount);}
}

4.3.2.GetDbInfoService.java

package cn.nordrassil.db2doc;import cn.nordrassil.db2doc.dto.DbConnParamDTO;
import cn.nordrassil.db2doc.dto.DbInfoDTO;import java.util.List;public interface GetDbInfoService {List<DbInfoDTO> get(DbConnParamDTO dto);
}

5.依賴?

5.1.mave依賴

<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version><scope>compile</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.28</version><scope>provided</scope></dependency><!-- Apache Commons Compress 用于處理多種歸檔文件格式 --><dependency><groupId>org.apache.commons</groupId><artifactId>commons-compress</artifactId><version>1.24.0</version></dependency><!-- Apache Commons IO 提供了 IO 操作的工具類 --><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.13.0</version></dependency><dependency><groupId>com.github.junrar</groupId><artifactId>junrar</artifactId><version>7.5.5</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.2.3</version></dependency>

5.2.word文檔模板

word/word模板.docx · 楽焫旒璡/public-share - 碼云 - 開源中國

6.測試

6.1.MyTest.java

package cn.nordrassil.db2doc;import cn.nordrassil.db2doc.dto.DbConnParamDTO;
import cn.nordrassil.db2doc.dto.DbInfoDTO;
import cn.nordrassil.db2doc.dto.ExportWordParamDTO;
import cn.nordrassil.db2doc.impl.GetDbInfoKingBaseEsService;
import cn.nordrassil.db2doc.util.CommonUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;import java.io.File;
import java.util.ArrayList;
import java.util.List;public class MyTest {public static void main(String[] args) throws Exception {String exportFolder = System.getProperty("user.dir") + File.separator + "files";String templateFile = "F:\\文檔\\開發\\word模板.docx";String resultFile = exportFolder + File.separator + "result.json";//getDbInfo(resultFile);List<DbInfoDTO> ds = readData(resultFile);ExportWordParamDTO exportWordParamDTO = new ExportWordParamDTO(ds, templateFile, exportFolder, true);//DbInfoExportWordService.generateWord(exportWordParamDTO);}public static void getDbInfo(String resultFile) throws Exception {GetDbInfoService getDbInfoService = new GetDbInfoKingBaseEsService();List<DbInfoDTO> dbInfoDTOS = getDbInfoService.get(new DbConnParamDTO("192.168.1.1",5432,"root","123456","test","test",true));CommonUtil.writeString(JSONObject.toJSONString(dbInfoDTOS), resultFile);}public static List<DbInfoDTO> readData(String resultFile) {JSONArray jas = JSONObject.parseArray(CommonUtil.readByLineRs(resultFile));List<DbInfoDTO> ds = new ArrayList<>();for (int i = 0; i < jas.size(); i++) {JSONObject ja = jas.getJSONObject(i);DbInfoDTO dbInfo = new DbInfoDTO();dbInfo.setDbName(ja.getString("dbName"));dbInfo.setDbDescribe(ja.getString("dbDescribe"));List<DbInfoDTO.TableInfo> tableInfos = new ArrayList<>();dbInfo.setTableInfos(tableInfos);JSONArray tis = ja.getJSONArray("tableInfos");for (int k = 0; k < tis.size(); k++) {JSONObject ti = tis.getJSONObject(k);DbInfoDTO.TableInfo tableInfo = new DbInfoDTO.TableInfo();tableInfos.add(tableInfo);tableInfo.setTableName(ti.getString("tableName"));tableInfo.setTableDescribe(ti.getString("tableDescribe"));JSONArray tfs = ti.getJSONArray("tableFields");List<DbInfoDTO.TableField> tableFields = new ArrayList<>();tableInfo.setTableFields(tableFields);for (int j = 0; j < tfs.size(); j++) {JSONObject tf = tfs.getJSONObject(j);tableFields.add(new DbInfoDTO.TableField(tf.getString("name"),tf.getString("type"),tf.getInteger("length"),tf.getString("allowEmpty"),tf.getString("isPrimaryKey"),tf.getString("defaultValue"),tf.getString("describe")));}}ds.add(dbInfo);}return ds;}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/78575.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/78575.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/78575.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Qt中的全局函數講解集合(全)

在頭文件<QtGlobal>中包含了Qt的全局函數&#xff0c;現在就這些全局函數一一詳解。 1.qAbs 原型&#xff1a; template <typename T> T qAbs(const T &t)一個用于計算絕對值的函數。它可以用于計算各種數值類型的絕對值&#xff0c;包括整數、浮點數等 示…

AI與IT協同的典型案例

簡介 本篇代碼示例展示了IT從業者如何與AI協同工作&#xff0c;發揮各自優勢。這些案例均來自2025年的最新企業實踐&#xff0c;涵蓋了不同IT崗位的應用場景。 一、GitHub Copilot生成代碼框架 開發工程師AI協作示例&#xff1a;利用GitHub Copilot生成代碼框架&#xff0c;…

三網通電玩城平臺系統結構與源碼工程詳解(二):Node.js 服務端核心邏輯實現

本篇文章將聚焦服務端游戲邏輯實現&#xff0c;以 Node.js Socket.io 作為主要通信與邏輯處理框架&#xff0c;展開用戶登錄驗證、房間分配、子游戲調度與事件廣播機制的剖析&#xff0c;并附上多個核心代碼段。 一、服務端文件結構概覽 /server/├── index.js …

【prompt是什么?有哪些技巧?】

Prompt&#xff08;提示詞&#xff09;是什么&#xff1f; Prompt 是用戶輸入給AI模型&#xff08;如ChatGPT、GPT-4等&#xff09;的指令或問題&#xff0c;用于引導模型生成符合預期的回答。它的質量直接影響AI的輸出效果。 Prompt 的核心技巧 1. 明確目標&#xff08;Clar…

堆和二叉樹--數據結構初階(3)(C/C++)

文章目錄 前言理論部分堆的模擬實現:(這里舉的大根堆)堆的創建二叉樹的遍歷二叉樹的一些其他功能實現 作業部分 前言 這期的話講解的是堆和二叉樹的理論部分和習題部分 理論部分 二叉樹的幾個性質:1.對于任意一個二叉樹&#xff0c;度為0的節點比度為2的節點多一個 2.對于完全…

Dockerfile講解與示例匯總

容器化技術已經成為應用開發和部署的標準方式,而Docker作為其中的佼佼者,以其輕量、高效、可移植的特性,深受開發者和運維人員的喜愛。本文將從實用角度出發,分享各類常用服務的Docker部署腳本與最佳實踐,希望能幫助各位在容器化之路上少走彎路。 無論你是剛接觸Docker的…

在QGraphicsView中精確地以鼠標為錨縮放圖片

在pyqt中以鼠標所在位置為錨點縮放圖片-CSDN博客中的第一個示例中&#xff0c;通過簡單設置&#xff1a; self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) 使得QGraphicsView具有了以鼠標為錨進行縮放的功能。但是&#xff0c;其內部應當是利用了滾動條的移動來…

制造工廠如何借助電子看板實現高效生產管控

在當今高度競爭的制造業環境中&#xff0c;許多企業正面臨著嚴峻的管理和生產挑戰。首先&#xff0c;管理流程落后&#xff0c;大量工作仍依賴"人治"方式&#xff0c;高層管理者理論知識薄弱且不愿聽取專業意見。其次&#xff0c;生產過程控制能力不足&#xff0c;導…

在 C# .NET 中駕馭 JSON:使用 Newtonsoft.Json 進行解析與 POST 請求實戰

JSON (JavaScript Object Notation) 已經成為現代 Web 應用和服務之間數據交換的通用語言。無論你是開發后端 API、與第三方服務集成&#xff0c;還是處理配置文件&#xff0c;都繞不開 JSON 的解析與生成。在 C# .NET 世界里&#xff0c;處理 JSON 有多種選擇&#xff0c;其中…

Debian10系統安裝,磁盤分區和擴容

1、說明 過程記錄信息有些不全&#xff0c;僅作為參考。如有其它疑問&#xff0c;歡迎留言。 2、ISO下載 地址&#xff1a;debian-10.13.0鏡像地址 3、開始安裝 3.1、選擇圖形界面 3.2、選擇中文語言 3.3、選擇中國區域 3.4、按照提示繼續 3.5、選擇一個網口 3.6、創建管…

1.10軟考系統架構設計師:優秀架構設計師 - 練習題附答案及超詳細解析

優秀架構設計師綜合知識單選題 每道題均附有答案解析&#xff1a; 題目1 衡量優秀系統架構設計師的核心標準不包括以下哪項&#xff1f; A. 技術全面性與底層系統原理理解 B. 能夠獨立完成模塊開發與調試 C. 與利益相關者的高效溝通與協調能力 D. 對業務需求和技術趨勢的戰略…

MPI Code for Ghost Data Exchange in 3D Domain Decomposition with Multi-GPUs

MPI Code for Ghost Data Exchange in 3D Domain Decomposition with Multi-GPUs Here’s a comprehensive MPI code that demonstrates ghost data exchange for a 3D domain decomposition across multiple GPUs. This implementation assumes you’re using CUDA-aware MPI…

計算機考研精煉 計網

第 19 章 計算機網絡體系結構 19.1 基本概念 19.1.1 計算機網絡概述 1.計算機網絡的定義、組成與功能 計算機網絡是一個將分散的、具有獨立功能的計算機系統&#xff0c;通過通信設備與線路連接起來&#xff0c;由功能完善的軟件實現資源共享和信息傳遞的系統。 …

KUKA機器人自動備份設置

在機器人的使用過程中&#xff0c;對機器人做備份不僅能方便查看機器人的項目配置與程序&#xff0c;還能防止機器人項目和程序丟失時進行及時的還原&#xff0c;因此對機器人做備份是很有必要的。 對于KUKA機器人來說&#xff0c;做備份可以通過U盤來操作。也可以在示教器上設…

【wpf】 WPF中實現動態加載圖片瀏覽器(邊滾動邊加載)

WPF中實現動態加載圖片瀏覽器&#xff08;邊滾動邊加載&#xff09; 在做圖片瀏覽器程序時&#xff0c;遇到圖片數量巨大的情況&#xff08;如幾百張、上千張&#xff09;&#xff0c;一次性加載所有圖片會導致界面卡頓甚至程序崩潰。 本文介紹一種 WPF Prism 實現動態分頁加…

Kubernetes》》k8s》》Taint 污點、Toleration容忍度

污點 》》 節點上 容忍度 》》 Pod上 在K8S中&#xff0c;如果Pod能容忍某個節點上的污點&#xff0c;那么Pod就可以調度到該節點。如果不能容忍&#xff0c;那就無法調度到該節點。 污點和容忍度的概念 》》污點等級——>node 》》容忍度 —>pod Equal——>一種是等…

SEO長尾關鍵詞優化核心策略

內容概要 在搜索引擎優化領域&#xff0c;長尾關鍵詞因其精準的流量捕獲能力與較低的競爭強度&#xff0c;已成為提升網站自然流量的核心突破口。本文圍繞長尾關鍵詞優化的全鏈路邏輯&#xff0c;系統拆解從需求洞察到落地執行的五大策略模塊&#xff0c;涵蓋用戶搜索意圖解析…

AWS中國區ICP備案全攻略:流程、注意事項與最佳實踐

導語 在中國大陸地區開展互聯網業務時,所有通過域名提供服務的網站和應用必須完成ICP備案(互聯網內容提供商備案)。對于選擇使用AWS中國區(北京/寧夏區域)資源的用戶,備案流程因云服務商的特殊運營模式而有所不同。本文將詳細解析AWS中國區備案的核心規則、操作步驟及避坑…

計算機視覺——通過 OWL-ViT 實現開放詞匯對象檢測

介紹 傳統的對象檢測模型大多是封閉詞匯類型&#xff0c;只能識別有限的固定類別。增加新的類別需要大量的注釋數據。然而&#xff0c;現實世界中的物體類別幾乎無窮無盡&#xff0c;這就需要能夠檢測未知類別的開放式詞匯類型。對比學習&#xff08;Contrastive Learning&…

大語言模型的“模型量化”詳解 - 04:KTransformers MoE推理優化技術

基本介紹 隨著大語言模型&#xff08;LLM&#xff09;的規模不斷擴大&#xff0c;模型的推理效率和計算資源的需求也在迅速增加。DeepSeek-V2作為當前熱門的LLM之一&#xff0c;通過創新的架構設計與優化策略&#xff0c;在資源受限環境下實現了高效推理。 本文將詳細介紹Dee…