多选列表
《Excelize 权威指南》图书出版,网上购买方式:人民邮电出版社 |异步社区 |天猫 |京东 |当当 |微店 |抖音 |拼多多
使用 Go 语言在 Excel 文档中无需 VBA 创建可多选菜单列表:
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
)
func main() {
// 创建工作簿
f := excelize.NewFile()
var (
sheetName = "Sheet1"
selection = []string{"red", "blue", "green", "yellow"}
// 定义单元格的值
data = [][]interface{}{
{"Element", "Picklist", nil, "Select below"},
{selection[0] + " "},
{selection[1] + " "},
{selection[2] + " "},
{selection[3] + " "},
}
cell string
err error
)
// 按行赋值
for r, row := range data {
if cell, err = excelize.JoinCellName("A", r+1); err != nil {
fmt.Println(err)
return
}
if err = f.SetSheetRow(sheetName, cell, &row); err != nil {
fmt.Println(err)
return
}
}
// 设置自定义名称
for index, value := range selection {
if cell, err = excelize.CoordinatesToCellName(1, index+2, true); err != nil {
fmt.Println(err)
return
}
if err = f.SetDefinedName(&excelize.DefinedName{
Name: value,
RefersTo: fmt.Sprintf("%s!%s", sheetName, cell),
Scope: sheetName,
}); err != nil {
fmt.Println(err)
return
}
if cell, err = excelize.CoordinatesToCellName(2, index+2); err != nil {
fmt.Println(err)
return
}
formula := fmt.Sprintf("=IF(ISNUMBER(FIND(%s,D2)),\"\",D2&%s)", value, value)
if err := f.SetCellFormula(sheetName, cell, formula); err != nil {
fmt.Println(err)
return
}
}
// 设置数据验证
dv := excelize.NewDataValidation(true)
dv.SetSqref("D2:D2")
dv.SetSqrefDropList("$B$2:$B$5")
if err = f.AddDataValidation(sheetName, dv); err != nil {
fmt.Println(err)
return
}
// 自定义列宽
for col, width := range map[string]float64{"A": 10, "B": 18, "D": 18} {
if err = f.SetColWidth(sheetName, col, col, width); err != nil {
fmt.Println(err)
return
}
}
// 创建表格
if err = f.AddTable(sheetName,
&excelize.Table{
Range: "A1:B5",
Name: "table",
StyleName: "TableStyleMedium2",
},
); err != nil {
fmt.Println(err)
return
}
// 保存工作簿
if err := f.SaveAs("Book1.xlsx"); err != nil {
fmt.Println(err)
}
}