在Golang中的该列的下拉选项中生成具有指定值的CSV/Excel

wwtsj6pe  于 2023-07-31  发布在  Go
关注(0)|答案(3)|浏览(128)

如何在Golang中生成csv/excel,其中在该csv/excel中的某些列中将具有下拉选项,以便任何尝试添加/更新该列上的值的人都可以使用下拉列表中的可用值。
举例来说:在excel文件下方,航空公司列在下拉列表中列出了指定值。
P.S:下面的excel是在java中使用poi-4.0.0.jar库生成的
编辑1:我已经采取了不同的方法来解决上述问题,在这里分享https://go.dev/play/p/WD-qpXh6JNg
x1c 0d1x的数据

dohp0rv5

dohp0rv51#

试试看:

package main

import (
    "github.com/tealeg/xlsx"
)

func main() {
    file := xlsx.NewFile()
    sheet, _ := file.AddSheet("Sheet1")
    row := sheet.AddRow()
    cell := row.AddCell()
    cell.Value = "Column 1"
    cell = row.AddCell()
    cell.Value = "Column 2 (Dropdown)"

    dropdownValues := []string{"hi", "there"}

    for i := 0; i < 10; i++ {
        row := sheet.AddRow()
        cell := row.AddCell()
        cell.Value = fmt.Sprintf("Test %d", i)

        cell = row.AddCell()
        cell.SetDataValidationList(dropdownValues)
    }

  file.Save("output.xlsx")
}

字符串

tquggr8v

tquggr8v2#

Excel上的下拉列表是您可以使用此库的DataValidations:https://github.com/qax-os/excelize/
下面是一个简单的例子:

// create new file 
f := excelize.NewFile()
defer func() {
    if err := f.Close(); err != nil {
        fmt.Println(err)
    }
}()
index, err := f.NewSheet("Sheet2")
if err != nil {
    fmt.Println(err)
    return
}
// Create the new Data Validation
dv := excelize.NewDataValidation(true)
// add the keys that you want for your droplist
myKeys := []string{"test,test2"}
// add the keys to your drop list
dv.SetDropList(myKeys)
// What cells will be the dropdown list
dv.Sqref = "A1:A1"
// Add the datavalidation to your sheet
f.AddDataValidation("Sheet2", dv)
f.SetActiveSheet(index)
f.SaveAs("bok1.xlsx")

字符串

368yc8dk

368yc8dk3#

正如@andrew-arrow所建议的,我看了一下tealeg库,我能够得到想要的结果,完整的代码是here
再次感谢@andrew-arrow:)

file := xlsx.NewFile()
sheet, _ := file.AddSheet("Sheet1")
row := sheet.AddRow()
cell := row.AddCell()
cell.Value = "Column 1"
cell = row.AddCell()
cell.Value = "Column 2 (Dropdown)"

dropdownValues := []string{"AI | AirIndia", "UK | Vistara"}

for i := 0; i < 10; i++ {
    row := sheet.AddRow()
    cell := row.AddCell()
    cell.Value = fmt.Sprintf("Test %d", i)

    cell = row.AddCell()
    dd := xlsx.NewXlsxCellDataValidation(true)
    dd.SetDropList(dropdownValues)
    cell.SetDataValidation(dd)
}

file.Save("output.xlsx")

字符串
output.xlsx x1c 0d1x的快照

相关问题