当前位置: 首页 > wzjs >正文

广州建设行业网站网站建设应该考虑哪些问题

广州建设行业网站,网站建设应该考虑哪些问题,设计网站的一般过程,域名关联网站一、背景 遇到需求&#xff1a;将指定数据库表设计&#xff0c;统一导出到一个Excel中&#xff0c;存档查看。 如果一个一个弄&#xff0c;很复杂&#xff0c;耗时长。 二、写一个工具导出下 废话少絮&#xff0c;上码&#xff1a; 2.1 pom导入 <dependency><grou…

在这里插入图片描述

一、背景

遇到需求:将指定数据库表设计,统一导出到一个Excel中,存档查看。
如果一个一个弄,很复杂,耗时长。

二、写一个工具导出下

废话少絮,上码:

2.1 pom导入

		<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>5.4.0</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>5.4.0</version></dependency>

2.2 工具类

这里提供思路和示例

package com.eduer.books.modules.app.controller;import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.FileOutputStream;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;/*** Java导出mysql数据库表结构信息到excel* @author wangdy* 2025/3/13*/
public class DatabaseExporter {private static final Pattern INVALID_SHEETNAME_CHARS = Pattern.compile("[\\\\/*?\\[\\]:]");private static final int MAX_SHEETNAME_LENGTH = 31;public static void exportToExcel(String dbName, String jdbcUrl, String username, String password, String outputPath)throws Exception {Set<String> usedSheetNames = new HashSet<>();try (Workbook workbook = new XSSFWorkbook(); Connection conn = DriverManager.getConnection(jdbcUrl, username, password)) {DatabaseMetaData metaData = conn.getMetaData();ResultSet tables = metaData.getTables(dbName, null, "%", new String[]{"TABLE"});while (tables.next()) {String catalog = tables.getString("TABLE_CAT");String schema = tables.getString("TABLE_SCHEM");String tableName = tables.getString("TABLE_NAME");// 生成合法的Sheet名称String baseSheetName = generateBaseSheetName(catalog, schema, tableName);String uniqueSheetName = generateUniqueSheetName(baseSheetName, usedSheetNames);Sheet sheet = workbook.createSheet(uniqueSheetName);usedSheetNames.add(uniqueSheetName);createHeaderRow(sheet);processTableColumns(metaData, tableName, sheet);autoSizeColumns(sheet, 7);}try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {workbook.write(outputStream);}}}private static String generateBaseSheetName(String catalog, String schema, String tableName) {// 优先使用schema信息,MySQL中一般用catalog表示数据库String prefix = "";if (schema != null && !schema.isEmpty()) {prefix = schema;} else if (catalog != null && !catalog.isEmpty()) {prefix = catalog;}String rawName = prefix.isEmpty()? tableName: prefix + "_" + tableName;// 替换非法字符并格式化return formatSheetName(rawName);}private static String formatSheetName(String rawName) {// 1. 替换非法字符String sanitized = INVALID_SHEETNAME_CHARS.matcher(rawName).replaceAll("_");// 2. 去除首尾特殊字符sanitized = sanitized.replaceAll("^[\\s']+", "").replaceAll("[\\s']+$", "");// 3. 压缩连续下划线sanitized = sanitized.replaceAll("_{2,}", "_");// 4. 截断长度return sanitized.length() > MAX_SHEETNAME_LENGTH? sanitized.substring(0, MAX_SHEETNAME_LENGTH): sanitized;}private static String generateUniqueSheetName(String baseName, Set<String> usedNames) {if (!usedNames.contains(baseName)) {return baseName;}int suffix = 1;String candidateName;do {String suffixStr = "_" + suffix++;int maxBaseLength = MAX_SHEETNAME_LENGTH - suffixStr.length();candidateName = (baseName.length() > maxBaseLength? baseName.substring(0, maxBaseLength): baseName) + suffixStr;} while (usedNames.contains(candidateName));return candidateName;}private static void processTableColumns(DatabaseMetaData metaData, String tableName, Sheet sheet)throws SQLException {ResultSet columns = metaData.getColumns(null, null, tableName, null);Set<String> primaryKeys = getPrimaryKeys(metaData, tableName);int rowNum = 1;while (columns.next()) {Row row = sheet.createRow(rowNum++);fillRowData(columns, primaryKeys, row);}columns.close();}// 以下方法保持不变(createHeaderRow, createHeaderStyle, getPrimaryKeys, fillRowData, autoSizeColumns)private static void createHeaderRow(Sheet sheet) {Row headerRow = sheet.createRow(0);String[] headers = {"字段名称", "字段类型", "长度", "是否主键", "允许空值", "默认值", "字段注释"};CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());for (int i = 0; i < headers.length; i++) {Cell cell = headerRow.createCell(i);cell.setCellValue(headers[i]);cell.setCellStyle(headerStyle);}}private static CellStyle createHeaderStyle(Workbook workbook) {CellStyle style = workbook.createCellStyle();Font font = workbook.createFont();font.setBold(true);style.setFont(font);style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);return style;}private static Set<String> getPrimaryKeys(DatabaseMetaData metaData, String tableName) throws SQLException {Set<String> primaryKeys = new HashSet<>();ResultSet pkResultSet = metaData.getPrimaryKeys(null, null, tableName);while (pkResultSet.next()) {primaryKeys.add(pkResultSet.getString("COLUMN_NAME"));}pkResultSet.close();return primaryKeys;}private static void fillRowData(ResultSet columns, Set<String> primaryKeys, Row row) throws SQLException {String columnName = columns.getString("COLUMN_NAME");String typeName = columns.getString("TYPE_NAME");int columnSize = columns.getInt("COLUMN_SIZE");String isNullable = columns.getString("IS_NULLABLE");String defaultValue = columns.getString("COLUMN_DEF");String remarks = columns.getString("REMARKS");row.createCell(0).setCellValue(columnName);row.createCell(1).setCellValue(typeName);row.createCell(2).setCellValue(columnSize);row.createCell(3).setCellValue(primaryKeys.contains(columnName) ? "是" : "否");row.createCell(4).setCellValue("YES".equalsIgnoreCase(isNullable) ? "是" : "否");row.createCell(5).setCellValue(defaultValue != null ? defaultValue : "");row.createCell(6).setCellValue(remarks != null ? remarks : "");}private static void autoSizeColumns(Sheet sheet, int columnCount) {for (int i = 0; i < columnCount; i++) {sheet.autoSizeColumn(i);}}public static void main(String[] args) {try {String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/books-service?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";String username = "root";String password = "xxxxxxx";String outputPath = "数据库表结构.xlsx";exportToExcel("books-service", jdbcUrl, username, password, outputPath);System.out.println("导出成功!");} catch (Exception e) {e.printStackTrace();}}
}

main方法运行即可。

三、结果截图

在这里插入图片描述
在这里插入图片描述

四、扩展:导出到同一个sheet页

以上呢是将每个表导出到每个sheet页,有时候的需求是导出到同一个sheet页。可以用如下代码进行:

4.1 导出数据库表结构到excel中的同一个sheet页,并合并表名和表注释

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.FileOutputStream;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;/*** Java导出mysql数据库表结构信息到excel中的同一个sheet页,并合并表名和表注释* @author wangdy* 2025/3/14*/
public class DatabaseExporterToOneSheet {private static final Pattern INVALID_SHEETNAME_CHARS = Pattern.compile("[\\\\/*?\\[\\]:]");private static final int MAX_SHEETNAME_LENGTH = 31;public static void exportToExcel(String dbName, String jdbcUrl, String username, String password, String outputPath)throws Exception {Connection conn = null;Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet(dbName);try {conn = DriverManager.getConnection(jdbcUrl, username, password);DatabaseMetaData metaData = conn.getMetaData();ResultSet tables = metaData.getTables(dbName, null, "%", new String[]{"TABLE"});createHeaderRow(sheet);int rowNum = 1;int startRow = 1;int endRow = 1;while (tables.next()) {// String catalog = tables.getString("TABLE_CAT");// String schema = tables.getString("TABLE_SCHEM");String tableName = tables.getString("TABLE_NAME");String tableRemarks = tables.getString("REMARKS");ResultSet columns = metaData.getColumns(null, null, tableName, null);Set<String> primaryKeys = getPrimaryKeys(metaData, tableName);startRow = rowNum;while (columns.next()) {Row row = sheet.createRow(rowNum++);fillRowData(tableName, tableRemarks, columns, primaryKeys, row);}endRow = rowNum - 1;// 合并该表表名和表注释:new CellRangeAddress(0, 0, 0, 3)表示合并从第0行第0列到第0行第3列的区域。sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, 0, 0));sheet.addMergedRegion(new CellRangeAddress(startRow, endRow, 1, 1));columns.close();}autoSizeColumns(sheet, 9);try (FileOutputStream outputStream = new FileOutputStream(outputPath)) {workbook.write(outputStream);}} finally {if (conn != null) {conn.close();}workbook.close();}}private static String generateBaseSheetName(String catalog, String schema, String tableName) {// 优先使用schema信息,MySQL中一般用catalog表示数据库String prefix = "";if (schema != null && !schema.isEmpty()) {prefix = schema;} else if (catalog != null && !catalog.isEmpty()) {prefix = catalog;}String rawName = prefix.isEmpty()? tableName: prefix + "_" + tableName;// 替换非法字符并格式化return formatSheetName(rawName);}private static String formatSheetName(String rawName) {// 1. 替换非法字符String sanitized = INVALID_SHEETNAME_CHARS.matcher(rawName).replaceAll("_");// 2. 去除首尾特殊字符sanitized = sanitized.replaceAll("^[\\s']+", "").replaceAll("[\\s']+$", "");// 3. 压缩连续下划线sanitized = sanitized.replaceAll("_{2,}", "_");// 4. 截断长度return sanitized.length() > MAX_SHEETNAME_LENGTH? sanitized.substring(0, MAX_SHEETNAME_LENGTH): sanitized;}private static void createHeaderRow(Sheet sheet) {Row headerRow = sheet.createRow(0);String[] headers = {"表名称", "表注释", "字段名称", "字段类型", "长度", "是否主键", "允许空值", "默认值", "字段注释"};CellStyle headerStyle = createHeaderStyle(sheet.getWorkbook());for (int i = 0; i < headers.length; i++) {Cell cell = headerRow.createCell(i);cell.setCellValue(headers[i]);cell.setCellStyle(headerStyle);}}private static CellStyle createHeaderStyle(Workbook workbook) {CellStyle style = workbook.createCellStyle();Font font = workbook.createFont();font.setBold(true);style.setFont(font);style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());style.setFillPattern(FillPatternType.SOLID_FOREGROUND);return style;}private static Set<String> getPrimaryKeys(DatabaseMetaData metaData, String tableName) throws SQLException {Set<String> primaryKeys = new HashSet<>();ResultSet pkResultSet = metaData.getPrimaryKeys(null, null, tableName);while (pkResultSet.next()) {primaryKeys.add(pkResultSet.getString("COLUMN_NAME"));}pkResultSet.close();return primaryKeys;}private static void fillRowData(String tableName, String tableRemarks, ResultSet columns, Set<String> primaryKeys, Row row) throws SQLException {String columnName = columns.getString("COLUMN_NAME");String typeName = columns.getString("TYPE_NAME");int columnSize = columns.getInt("COLUMN_SIZE");String isNullable = columns.getString("IS_NULLABLE");String defaultValue = columns.getString("COLUMN_DEF");String remarks = columns.getString("REMARKS");row.createCell(0).setCellValue(tableName);row.createCell(1).setCellValue(tableRemarks);row.createCell(2).setCellValue(columnName);row.createCell(3).setCellValue(typeName);row.createCell(4).setCellValue(columnSize);row.createCell(5).setCellValue(primaryKeys.contains(columnName) ? "是" : "否");row.createCell(6).setCellValue("YES".equalsIgnoreCase(isNullable) ? "是" : "否");row.createCell(7).setCellValue(defaultValue != null ? defaultValue : "");row.createCell(8).setCellValue(remarks != null ? remarks : "");}private static void autoSizeColumns(Sheet sheet, int columnCount) {for (int i = 0; i < columnCount; i++) {sheet.autoSizeColumn(i, true);}}public static void main(String[] args) {try {String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/books-service?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";String username = "root";String password = "xxxxxx";String outputPath = "数据库表结构.xlsx";exportToExcel("books-service", jdbcUrl, username, password, outputPath);System.out.println("导出成功!");} catch (Exception e) {e.printStackTrace();}}
}

4.2 结果

结果如下图所示,非常Nice。
在这里插入图片描述

END


文章转载自:

http://DU0piDPO.bkryb.cn
http://F3LU5ScM.bkryb.cn
http://r4IgxWFF.bkryb.cn
http://DiaH79Su.bkryb.cn
http://QrJi9pgs.bkryb.cn
http://UTeYHmNs.bkryb.cn
http://FsKBQCmX.bkryb.cn
http://K6SxN3An.bkryb.cn
http://HKcs2cXS.bkryb.cn
http://EzAyILgM.bkryb.cn
http://u5v5Rk7r.bkryb.cn
http://yDhLWIO6.bkryb.cn
http://trpXkrle.bkryb.cn
http://MXBDcLSl.bkryb.cn
http://yZXz46jG.bkryb.cn
http://k4IigINi.bkryb.cn
http://fOToB0LQ.bkryb.cn
http://7CbodOep.bkryb.cn
http://IDiowMMt.bkryb.cn
http://UDxYJQxR.bkryb.cn
http://NuQypFzu.bkryb.cn
http://HQgMASr1.bkryb.cn
http://2uYwh3eP.bkryb.cn
http://fEFJyx95.bkryb.cn
http://WhstdW0O.bkryb.cn
http://cClp4LkE.bkryb.cn
http://BtFydEXJ.bkryb.cn
http://3e7IGV5L.bkryb.cn
http://Nc5AJrjY.bkryb.cn
http://R5P0H5Zq.bkryb.cn
http://www.dtcms.com/wzjs/736845.html

相关文章:

  • 物业公司网站建设广西网站建设哪家有
  • 网站做图尺寸大小可信网站友链怎么做
  • 兰溪做网站哪家好实体店引流推广方法
  • 营销型平台网站建设网站开发济南
  • 便宜的网站建设公司网站数据库
  • 暖色调网站欣赏北京高端网站建设系统
  • 梁山专做网站的公司娄底网站建设建站
  • 网站开发招聘年薪外贸网站啥需要掌握在自己手里
  • 吴江区建设工程招标网站东莞工信部网站
  • 长春建站的费用做网站需要了解什么东西
  • 商丘手机网站建设网站灰色 代码
  • 帝国cms手机网站模板平湖网站开发
  • 打字建站宝如何进行网络推广市场定位
  • 山阳网站建设福州网站建设案例
  • 果洛wap网站建设比较好seo排名快速刷
  • 电子商务网站建设的核心是什么南山做网站多少钱
  • php做的静态网站怎么加密wordpress 模拟数据
  • 纳溪区城乡住房建设局网站南京企业网站建设
  • 大连网站排名系统做网站点击量有用吗
  • seo引擎搜索网站海南省住房和城乡建设厅官网网站
  • DS716 II 做网站泰安网络信息化建设
  • 网站站点层叠样式怎么做合肥建设银行招聘网站
  • 北京建设银行官方网站ps网站怎么做滑动背景
  • 树莓派架设wordpressseo优化技术厂家
  • 推广型网站建设机构百度线上推广
  • 模板网站好还是定制网站好asp网站开发实验总结
  • 自己建网站硅胶东莞网站建设
  • 学做网站最好的网站外贸网站图片
  • 大型门户网站设计阳江网络推广公司
  • 如何建立一个网站预算多少怎么做网页设计原型