Golang Excel库 - 如何为特定列设置行数据

Golang Excel库 - 如何为特定列设置行数据 在 exclize 库中,如何仅为特定的 4 列设置行,以及如何为该单元格设置样式

1 回复

更多关于Golang Excel库 - 如何为特定列设置行数据的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在 exclize 库中,可以使用 SetCellValue 为特定列设置行数据,并通过 NewStyleSetCellStyle 设置单元格样式。以下是示例代码:

package main

import (
    "fmt"
    "github.com/xuri/excelize/v2"
)

func main() {
    f := excelize.NewFile()
    defer func() {
        if err := f.Close(); err != nil {
            fmt.Println(err)
        }
    }()

    // 定义要设置的列(A、C、E、G)
    columns := []string{"A", "C", "E", "G"}
    row := 5 // 第5行

    // 创建样式
    style, err := f.NewStyle(&excelize.Style{
        Font: &excelize.Font{Bold: true, Color: "FF0000"},
        Fill: excelize.Fill{Type: "pattern", Color: []string{"FFFF00"}, Pattern: 1},
    })
    if err != nil {
        fmt.Println(err)
        return
    }

    // 为每列设置数据和样式
    for i, col := range columns {
        cell := fmt.Sprintf("%s%d", col, row)
        
        // 设置数据
        value := fmt.Sprintf("数据%d", i+1)
        if err := f.SetCellValue("Sheet1", cell, value); err != nil {
            fmt.Println(err)
            return
        }
        
        // 应用样式
        if err := f.SetCellStyle("Sheet1", cell, cell, style); err != nil {
            fmt.Println(err)
            return
        }
    }

    // 保存文件
    if err := f.SaveAs("特定列设置.xlsx"); err != nil {
        fmt.Println(err)
    }
}

如果需要为整行设置样式但只填充特定列,可以这样调整:

// 设置整行样式
startCell := fmt.Sprintf("A%d", row)
endCell := fmt.Sprintf("G%d", row)
if err := f.SetCellStyle("Sheet1", startCell, endCell, style); err != nil {
    fmt.Println(err)
    return
}

// 只填充特定列的数据
data := map[string]interface{}{
    "A5": "列A数据",
    "C5": "列C数据", 
    "E5": "列E数据",
    "G5": "列G数据",
}

for cell, value := range data {
    if err := f.SetCellValue("Sheet1", cell, value); err != nil {
        fmt.Println(err)
        return
    }
}

对于多行操作,可以使用循环:

rows := []int{5, 6, 7}
for _, row := range rows {
    for i, col := range columns {
        cell := fmt.Sprintf("%s%d", col, row)
        value := fmt.Sprintf("行%d-数据%d", row, i+1)
        f.SetCellValue("Sheet1", cell, value)
        f.SetCellStyle("Sheet1", cell, cell, style)
    }
}
回到顶部