多选列表

使用 Go 语言在 Excel 文档中无需 VBA 创建可多选菜单列表:

使用 Go 语言在 Excel 文档中无需 VBA 创建可多选菜单列表

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/xuri/excelize/v2"
  5. )
  6. func main() {
  7. // 创建工作簿
  8. f := excelize.NewFile()
  9. var (
  10. sheetName = "Sheet1"
  11. selection = []string{"red", "blue", "green", "yellow"}
  12. // 定义单元格的值
  13. data = [][]interface{}{
  14. {"Element", "Picklist", nil, "Select below"},
  15. {selection[0] + " "},
  16. {selection[1] + " "},
  17. {selection[2] + " "},
  18. {selection[3] + " "},
  19. }
  20. cell string
  21. err error
  22. )
  23. // 按行赋值
  24. for r, row := range data {
  25. if cell, err = excelize.JoinCellName("A", r+1); err != nil {
  26. fmt.Println(err)
  27. return
  28. }
  29. if err = f.SetSheetRow(sheetName, cell, &row); err != nil {
  30. fmt.Println(err)
  31. return
  32. }
  33. }
  34. // 设置自定义名称
  35. for index, value := range selection {
  36. if cell, err = excelize.CoordinatesToCellName(1, index+2, true); err != nil {
  37. fmt.Println(err)
  38. return
  39. }
  40. if err = f.SetDefinedName(&excelize.DefinedName{
  41. Name: value,
  42. RefersTo: fmt.Sprintf("%s!%s", sheetName, cell),
  43. Scope: sheetName,
  44. }); err != nil {
  45. fmt.Println(err)
  46. return
  47. }
  48. if cell, err = excelize.CoordinatesToCellName(2, index+2); err != nil {
  49. fmt.Println(err)
  50. return
  51. }
  52. formula := fmt.Sprintf("=IF(ISNUMBER(FIND(%s,D2)),\"\",D2&%s)", value, value)
  53. if err := f.SetCellFormula(sheetName, cell, formula); err != nil {
  54. fmt.Println(err)
  55. return
  56. }
  57. }
  58. // 设置数据验证
  59. dvRange := excelize.NewDataValidation(true)
  60. dvRange.Sqref = "D2:D2"
  61. dvRange.SetSqrefDropList("$B$2:$B$5")
  62. if err = f.AddDataValidation(sheetName, dvRange); err != nil {
  63. fmt.Println(err)
  64. return
  65. }
  66. // 自定义列宽
  67. for col, width := range map[string]float64{"A": 10, "B": 18, "D": 18} {
  68. if err = f.SetColWidth(sheetName, col, col, width); err != nil {
  69. fmt.Println(err)
  70. return
  71. }
  72. }
  73. // 创建表格
  74. if err = f.AddTable(sheetName, "A1", "B5", `{
  75. "table_name": "table",
  76. "table_style": "TableStyleMedium2"
  77. }`); err != nil {
  78. fmt.Println(err)
  79. return
  80. }
  81. // 保存工作簿
  82. if err := f.SaveAs("Book1.xlsx"); err != nil {
  83. fmt.Println(err)
  84. }
  85. }