原创不易,未经允许,请勿转载。

gormhttps://github.com/carmel/gooxml

首先获取数据库中所有表的表名

func GetTables() []string {
	var tables []string
	db.Raw("show tables").Scan(&tables)

	return tables
}

封装一个实体类用来接受表的字段信息

type Result struct {
	ColumnName    string `gorm:"column:COLUMN_NAME"` // 字段名
	ColumnType    string `gorm:"column:COLUMN_TYPE"` // 字段类型
	IsNullable    string `gorm:"column:IS_NULLABLE"` // 是否为空
	ColumnKey     string `gorm:"column:COLUMN_KEY"`  // 字段键
	ColumnComment string `gorm:"column:COLUMN_COMMENT"` // 字段注释
}
conf.DataSource.Dbname
func GetTableInfo(tableName string) []Result {
	results := make([]Result, 0)
	db.Raw("select column_name,column_type,is_nullable,column_key, column_comment from information_schema.columns where table_schema =?  and table_name = ?",conf.DataSource.Dbname, tableName).Scan(&results)
	return results
}

把表字段信息写入word中

type Writer struct {
	doc *document.Document
}

func NewWriter() *Writer {
	doc := document.New()
	return &Writer{doc: doc}
}

func (w *Writer) WriterTable(tableName string, tableInfo []Result) {
	// 写入表名
	w.doc.AddParagraph().AddRun().AddText(tableName)

	// 添加一个表格
	table := w.doc.AddTable()
	// width of the page
	table.Properties().SetWidthPercent(100)
	// with thick borers
	borders := table.Properties().Borders()
	borders.SetAll(wml.ST_BorderSingle, color.Auto, measurement.Zero)
	row := table.AddRow()
	row.AddCell().AddParagraph().AddRun().AddText("字段编号")
	row.AddCell().AddParagraph().AddRun().AddText("字段名")
	row.AddCell().AddParagraph().AddRun().AddText("字段类型")
	row.AddCell().AddParagraph().AddRun().AddText("是否为空")
	row.AddCell().AddParagraph().AddRun().AddText("字段键")
	row.AddCell().AddParagraph().AddRun().AddText("备注")

	for idx, val := range tableInfo {
		row = table.AddRow()
		row.AddCell().AddParagraph().AddRun().AddText(fmt.Sprintf("%d", idx+1))
		row.AddCell().AddParagraph().AddRun().AddText(val.ColumnName)
		row.AddCell().AddParagraph().AddRun().AddText(val.ColumnType)
		row.AddCell().AddParagraph().AddRun().AddText(val.IsNullable)
		row.AddCell().AddParagraph().AddRun().AddText(val.ColumnKey)
		row.AddCell().AddParagraph().AddRun().AddText(val.ColumnComment)
	}
	w.doc.AddParagraph()
}

func (w *Writer) Save(fileName string) error {
	return w.doc.SaveToFile(fileName)
}
func main() {
	tables := GetTables()
	writer := NewWriter()
	for _, tableName := range tables {
		results := GetTableInfo(tableName)
		writer.WriterTable(tableName, results)
	}
	writer.Save(fmt.Sprintf("%s.docx",conf.DataSource.Dbname))
}

拒绝白嫖从一键三连开始!

原创不易,未经允许,请勿转载。