0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GolangのExcelizeを利用してセルの背景色のみを変更する

Posted at

1.概要

Excelizeでは元となったExcelのテンプレート上のセルの色を変更しようとすると、フォントや罫線など他の設定も初期化されてしまい背景色のみを変更することができなかった。

The cell color how to set? Can give a simple example? #254
https://github.com/qax-os/excelize/issues/254

しかしissueでもあるようにExcelize v2.8.0からセルのフォントや罫線を保持した状態で背景色のみ変更できる様になった。
以下にサンプルとなるコードを記載する。

2.サンプルコード (名簿リストの内、不在者の列をグレーアウトする)

sample.go
if fuzai,ok := latest_fuzailist[item.KJID]; ok{
            print_fuzai := checkDateFlag(fuzai.GaisyutuDate,fuzai.KiinDate)
            _ = f.SetCellValue(mainSheet , fmt.Sprintf("C%d", print_row), print_fuzai)                        
            if print_fuzai == "不在" {
                for col := 'A'; col <= 'M'; col++ {
                    cell := fmt.Sprintf("%c%d", col, print_row) 
                    styleID, err := f.GetCellStyle(mainSheet,cell) //スタイルインデックスの取得
                    if err != nil {
                        panic(err)
                    }
                    style,err := f.GetStyle(styleID) //スタイル定義を取得する
                    if err != nil {
                        panic(err)
                    }
                    //スタイル定義に基づいてスタイルを変更または追加する ※今回は背景をグレーアウトする
                    style.Fill = excelize.Fill{
                        Type: "pattern",
                        Color: []string{"#C0C0C0"},
                        Pattern: 1,
                    }

                    newStyleID, err := f.NewStyle(style) //新しいスタイルを作成する
                    if err != nil {
                        panic(err)
                    }
                    _ = f.SetCellStyle(mainSheet, cell, cell, newStyleID) //変更したセルのスタイルを設定する
                }
            }
            
        }

3.まとめ

ExcelizeではExcel上のデータ処理は数多くの多くが可能であったが、罫線やフォントを設定しているセルの背景色を変更することが困難であった。
今回のアップデートではあらかじめ帳票としてテンプレートの罫線やフォントを指定した状態での帳票の背景色を変更できるようになった為、テンプレートでの活用の幅が広がると思うので知識を共有したい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?