go-ole / go-ole

win32 ole implementation for golang
MIT License
1.16k stars 195 forks source link

Excel how to add styles #214

Open jontxux opened 3 years ago

jontxux commented 3 years ago

I have the following code, I would like to add colour to the cell background and change the font colour. Can someone help me?

// +build windows

package main

import (
    "log"
    "os"

    ole "github.com/go-ole/go-ole"
    "github.com/go-ole/go-ole/oleutil"
)

func main() {
    cwd, _ := os.Getwd()
    file := cwd + "\\Swap_con_CdM_OPERACIONES_E1_V5___2043397.xlsx"
    ole.CoInitialize(0)
    unknown, _ := oleutil.CreateObject("Excel.Application")
    excel, _ := unknown.QueryInterface(ole.IID_IDispatch)

    workbooks := oleutil.MustGetProperty(excel, "Workbooks").ToIDispatch()
    workbook, err := oleutil.CallMethod(workbooks, "Open", file)

    worksheet := oleutil.MustGetProperty(workbook.ToIDispatch(), "Worksheets", 1).ToIDispatch()
    defer worksheet.Release()

    cell := oleutil.MustGetProperty(worksheet, "Cells", 1, 1).ToIDispatch()
    oleutil.PutProperty(cell, "Value", 12345)
    cell.Release()
    oleutil.PutProperty(excel, "DisplayAlerts", false)

    oleutil.MustCallMethod(workbook.ToIDispatch(), "SaveAs", file, 51, nil, nil).ToIDispatch()

    if err != nil {
        log.Fatalln(err)
    }
    defer workbook.ToIDispatch().Release()
    workbooks.Release()
    oleutil.CallMethod(excel, "Quit")
    excel.Release()
    ole.CoUninitialize()

}
CarsonSlovoka commented 1 year ago

change the font color

vCell, _ := worksheet.PropertyGet("Cells", 1, 1)
font := vCell.ToIDispatch().MustPropertyGet("Font").ToIDispatch()
// font.MustPropertyPut("Color", int32(w32.RGB(0xff, 0xff, 0x00))) // yellow
font.MustPropertyPut("Color", int32((0x00<<16)|(0xff<<8)|0xff)) // yellow, BGR

Reference: