Golang实现 - 实现只有表头的 Excel 模板,并在指定列添加了下拉框功能。生成的 Excel 文件在打开时,指定列的单元格会显示下拉选项

该版本完全兼容最新版 excelize 库 (v2.7+),实现了只有表头的 Excel 模板,并在指定列添加了下拉框功能。生成的 Excel 文件在打开时,指定列的单元格会显示下拉选择箭头。

代码如下:

Go 复制代码
package main

import (
	"fmt"
	"log"

	"github.com/xuri/excelize/v2"
)

// Excel模板配置
type ExcelTemplateConfig struct {
	SheetName    string         // 工作表名称
	Headers      []HeaderConfig // 表头配置
	DropdownCols []DropdownCol  // 下拉框列配置
}

type HeaderConfig struct {
	Title  string // 列标题
	Column string // 列标识(如A, B, C)
}

type DropdownCol struct {
	Column   string   // 需要下拉框的列标识(如B, C)
	Options  []string // 下拉选项列表
	StartRow int      // 下拉框起始行(从1开始)
	EndRow   int      // 下拉框结束行
}

func CreateExcelTemplate(config ExcelTemplateConfig) error {
	f := excelize.NewFile()
	defer f.Close()

	// 设置工作表名称
	sheet := config.SheetName
	if sheet == "" {
		sheet = "Sheet1"
	}

	// 创建新工作表
	index, err := f.NewSheet(sheet)
	if err != nil {
		return fmt.Errorf("创建工作表失败: %w", err)
	}
	f.SetActiveSheet(index)

	// 写入表头
	for _, header := range config.Headers {
		cell := fmt.Sprintf("%s1", header.Column)
		if err := f.SetCellValue(sheet, cell, header.Title); err != nil {
			return fmt.Errorf("写入表头失败: %w", err)
		}

		// 设置表头样式(可选)
		style, _ := f.NewStyle(&excelize.Style{
			Font:      &excelize.Font{Bold: true, Color: "FFFFFF"},
			Fill:      excelize.Fill{Type: "pattern", Color: []string{"4F81BD"}, Pattern: 1},
			Alignment: &excelize.Alignment{Horizontal: "center"},
		})
		f.SetCellStyle(sheet, cell, cell, style)
	}

	// 设置列宽(可选)
	for _, header := range config.Headers {
		colWidth := 15.0 // 默认列宽
		if len(header.Title) > 15 {
			colWidth = float64(len(header.Title)) + 2
		}
		if err := f.SetColWidth(sheet, header.Column, header.Column, colWidth); err != nil {
			log.Printf("设置列宽失败: %v", err)
		}
	}

	// 添加下拉框
	for _, dropdown := range config.DropdownCols {
		if dropdown.EndRow < dropdown.StartRow {
			// 默认设置1000行下拉框
			dropdown.EndRow = dropdown.StartRow + 999
		}

		// 构建范围字符串 (如 "B2:B1000")
		dvRange := fmt.Sprintf(
			"%s%d:%s%d",
			dropdown.Column,
			dropdown.StartRow,
			dropdown.Column,
			dropdown.EndRow,
		)

		// 创建数据验证对象
		dv := excelize.NewDataValidation(true) // 允许空值
		dv.SetSqref(dvRange)                   // 设置应用范围

		// 设置下拉列表选项
		if err := dv.SetDropList(dropdown.Options); err != nil {
			return fmt.Errorf("设置下拉选项失败: %w", err)
		}

		// 添加数据验证到工作表
		if err := f.AddDataValidation(sheet, dv); err != nil {
			return fmt.Errorf("添加下拉框失败: %w", err)
		}

		// 添加注释提示(使用新版API)
		commentCell := fmt.Sprintf("%s1", dropdown.Column)
		if err := f.AddComment(sheet, excelize.Comment{
			Cell:   commentCell,
			Author: "系统提示",
			Paragraph: []excelize.RichTextRun{
				{Text: "请从下拉列表中选择:\n"},
				{Text: joinOptions(dropdown.Options)},
			},
		}); err != nil {
			log.Printf("添加注释失败: %v", err)
		}
	}

	// 保存文件
	if err := f.SaveAs("template.xlsx"); err != nil {
		return fmt.Errorf("保存文件失败: %w", err)
	}

	return nil
}

// 将选项列表转换为逗号分隔的字符串(用于注释)
func joinOptions(options []string) string {
	result := ""
	for i, opt := range options {
		if i > 0 {
			result += ", "
		}
		result += opt
	}
	return result
}

func main() {
	// 配置Excel模板
	config := ExcelTemplateConfig{
		SheetName: "Sheet1",
		Headers: []HeaderConfig{
			{Title: "产品ID", Column: "A"},
			{Title: "产品名称", Column: "B"},
			{Title: "产品状态", Column: "C"},
			{Title: "产品类别", Column: "D"},
		},
		DropdownCols: []DropdownCol{
			{
				Column:   "C", // 状态列
				Options:  []string{"在售", "下架", "预售", "停产", "测试"},
				StartRow: 2,    // 从第2行开始
				EndRow:   1000, // 到第1000行
			},
			{
				Column:   "D", // 类别列
				Options:  []string{"电子产品", "家居用品", "服装", "食品", "图书", "ceshi"},
				StartRow: 2,
				EndRow:   1000,
			},
		},
	}

	// 生成Excel模板文件
	if err := CreateExcelTemplate(config); err != nil {
		log.Fatalf("生成模板失败: %v", err)
	}

	fmt.Println("Excel模板已成功生成: template.xlsx")
	fmt.Println("包含以下下拉框列:")
	for i, dropdown := range config.DropdownCols {
		fmt.Printf("%d. 列 %s: %v\n", i+1, dropdown.Column, dropdown.Options)
	}
}

功能说明:

  1. 纯表头模板

    • 只生成表头行(第1行)

    • 没有数据行

  2. 下拉框功能

    • 在指定列添加数据验证下拉框

    • 下拉框从第2行开始到指定结束行

    • 支持多个下拉框列

  3. 增强功能

    • 表头美化:加粗、居中、蓝底白字

    • 列宽自适应:根据标题长度自动调整列宽

    • 提示注释:在列标题添加下拉选项提示

    • 空值允许:允许单元格为空

使用说明:

  1. 安装依赖

    bash

    bash 复制代码
    go get github.com/xuri/excelize/v2
  2. 运行程序

    bash

    bash 复制代码
    go run main.go
  3. 输出文件

    • 生成 template.xlsx 文件

    • 打开后可以看到表头和下拉框设置

自定义选项:

  1. 修改下拉选项

    go

    Go 复制代码
    Options: []string{"选项1", "选项2", "选项3"},
  2. 调整下拉范围

    go

    Go 复制代码
    StartRow: 2,   // 从第2行开始
    EndRow:   500, // 到第500行
  3. 添加更多下拉列

    go

    Go 复制代码
    DropdownCols: []DropdownCol{
        {Column: "E", Options: []string{"是", "否"}, StartRow: 2, EndRow: 1000},
        // 添加更多列...
    },

该版本完全兼容最新版 excelize 库 (v2.7+),实现了只有表头的 Excel 模板,并在指定列添加了下拉框功能。生成的 Excel 文件在打开时,指定列的单元格会显示下拉选择箭头。

扩展:

自定义列宽:

定义config:

Go 复制代码
// 配置Excel模板
	config := ExcelTemplateConfig{
		SheetName: "Sheet1",
		Headers: []HeaderConfig{
			{Title: "产品ID", Column: "A", Width: 20},  // 增加了列宽的配置
			{Title: "产品名称", Column: "B", Width: 40},  // 增加了列宽的配置
			{Title: "产品状态", Column: "C"},
			{Title: "产品类别", Column: "D"},
		},
		DropdownCols: []DropdownCol{
			{
				Column:   "C", // 状态列
				Options:  []string{"在售", "下架", "预售", "停产", "测试"},
				StartRow: 2,      // 从第2行开始
				EndRow:   100000, // 到第100000行
			},
			{
				Column:   "D", // 类别列
				Options:  []string{"电子产品", "家居用品", "服装", "食品", "图书", "ceshi"},
				StartRow: 2,
				EndRow:   100000,
			},
		},
	}

设置列宽:

Go 复制代码
// 设置列宽(可选)
	   for _, header := range config.Headers {
		colWidth := 15.0 // 默认列宽
		if header.Width > 15 {
			colWidth = float64(header.Width)
		}
		if err := f.SetColWidth(sheet, header.Column, header.Column, colWidth); err != nil {
			log.Printf("设置列宽失败: %v", err)
		}
	}

修改这两处,即可按照用户设置的列宽来确定模板的列宽了。

相关推荐
Access开发易登软件21 小时前
Access开发一键删除Excel指定工作表
服务器·前端·后端·excel·vba·access·access开发
pk_xz1234561 天前
SAP全自动化工具开发:Excel自动上传与邮件通知系统
运维·人工智能·windows·深度学习·分类·自动化·excel
俊昭喜喜里2 天前
Excel——设置打印的区域
excel
开开心心就好2 天前
Excel数据合并工具:零门槛快速整理
运维·服务器·前端·智能手机·pdf·bash·excel
CodeCraft Studio3 天前
Aspose.Cells 应用案例:法国能源企业实现能源数据报告Excel自动化
自动化·excel·能源·aspose·aspose.cells·数据报告
人工智能训练师3 天前
将EXCEL或者CSV转换为键值对形式的Markdown文件
人工智能·excel
hmywillstronger3 天前
【Settlement】P1:整理GH中的矩形GRID角点到EXCEL中
android·excel
吹牛不交税3 天前
.NET使用EPPlus导出EXCEL的接口中,文件流缺少文件名信息
.net·excel
qyykaola4 天前
如何快速比较excel两列,拿出不同的数据
excel