使用 github.com/tealeg/xlsx 导出excel,设置样式无效

func main() {
    var file *xlsx.File
    var sheet *xlsx.Sheet
    var row *xlsx.Row
    var cell *xlsx.Cell
    var err error

    style := xlsx.NewStyle()

    fill := *xlsx.NewFill("solid", "00FF0000", "FF000000")
    font := *xlsx.NewFont(20, "Verdana")
    border := *xlsx.NewBorder("thin", "thin", "thin", "thin")

    style.Fill = fill
    style.Font = font
    style.Border = border

    style.ApplyFill = true
    style.ApplyFont = true
    style.ApplyBorder = true

    file = xlsx.NewFile()
    sheet = file.AddSheet("SheetName")
    row = sheet.AddRow()

    cell = row.AddCell()
    cell.Value = "100000"
    cell.SetStyle(style)

    cell = row.AddCell()
    cell.Value = "test"

    err = file.Save("D:\\test.xlsx")
    if err != nil {
        fmt.Printf(err.Error())
    }

}

只有字体设置是有效的

共 3 个回复


13638425827

请问这个问题解决了吗?我也一直遇到这个问题不知道怎么解决

# 0

cherish

有些属性是属于Cell的,需在cell中设置才能生效


func Makefile() error {
	file := xlsx.NewFile()
	sheet, err := file.AddSheet("sheet1")
	if err != nil {
		return err
	}

	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
	}
	style.Alignment = alignment
	style.ApplyAlignment = true

	row := sheet.AddRow()
	cell := row.AddCell()
	cell.Value = "测试一下"
	cell.SetStyle(style)

	cell.Merge(4, 0)
	row2 := sheet.AddRow()
	for i := 0; i < 5; i++ {
		name := row2.AddCell()
		name.Value = "掌声"
		name.SetStyle(style)
	}

	row3 := sheet.AddRow()
	mergeCell := row3.AddCell()
	mergeCell.Value = "合并"
	mergeCell.SetStyle(style)
	mergeCell.Merge(1, 1)

	row4 := sheet.AddRow()
	row4.AddCell()

	for i := 0; i < 10; i++ {
		row := sheet.AddRow()
		nameCell := row.AddCell()
		nameCell.Value = "xxx" + strconv.Itoa(i)

		ageCell := row.AddCell()
		ageCell.Value = strconv.Itoa(18)

		phoneCell := row.AddCell()
		phoneCell.Value = "stu.Phone"

		genderCell := row.AddCell()
		genderCell.Value = "stu.Gender"

		mailCell := row.AddCell()
		mailCell.Value = "stu.Mail"
	}

	err = file.Save("a.xlsl")
	if err != nil {
		return err
	}

	return nil
}

效果下如图:
WechatIMG248.png

# 1