Created
December 11, 2024 12:44
-
-
Save kujirahand/8362982cc06ac9516a7afbf96df0f31e to your computer and use it in GitHub Desktop.
カレンダーをExcelに書き込むプログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"time" | |
"github.com/xuri/excelize/v2" | |
) | |
func main() { | |
// 初期設定 --- (*1) | |
year := 2025 | |
templateFile := "template.xlsx" | |
weekdays := []string{"日", "月", "火", "水", "木", "金", "土"} | |
// テンプレートファイルを読み込む --- (*2) | |
xlsx, err := excelize.OpenFile(templateFile) | |
if err != nil { | |
log.Fatalf("テンプレートファイルの読み込みに失敗しました: %v\n", err) | |
} | |
// 1年分の月間カレンダ−を作成 --- (*3) | |
for month := 1; month <= 12; month++ { | |
// 対象月の開始日と終了日を取得 --- (*4) | |
startDate := time.Date(year, time.Month(month), 1, 0, 0, 0, 0, time.Local) | |
endDate := startDate.AddDate(0, 1, -1) // その月の最終日 | |
// 新規シートを作成してテンプレートの内容をコピー --- (*5) | |
sheetName := fmt.Sprintf("%d月", month) | |
newSheetIndex, _ := xlsx.NewSheet(sheetName) | |
xlsx.CopySheet(0, newSheetIndex) | |
// 月を指定 | |
xlsx.SetCellValue(sheetName, "A1", month) | |
// カレンダーの日付と曜日を記載 --- (*6) | |
row := 4 | |
for d := startDate; !d.After(endDate); d = d.AddDate(0, 0, 1) { | |
dateStr := d.Day() | |
weekdayStr := weekdays[d.Weekday()] | |
// セルに日付と曜日を記入 --- (*7) | |
a := fmt.Sprintf("A%d", row) | |
b := fmt.Sprintf("B%d", row) | |
d := fmt.Sprintf("D%d", row) | |
xlsx.SetCellValue(sheetName, a, dateStr) | |
xlsx.SetCellValue(sheetName, b, weekdayStr) | |
// 週末であれば背景色を変更 --- (*8) | |
if weekdayStr == "土" { | |
setCellBackgroundColor(xlsx, sheetName, a, d, "#E0E0FF") | |
} | |
if weekdayStr == "日" { | |
setCellBackgroundColor(xlsx, sheetName, a, d, "#FFE0E0") | |
} | |
row++ | |
} | |
} | |
// シートのテンプレートを削除 | |
xlsx.DeleteSheet("Sheet1") | |
// ファイル保存 --- (*9) | |
if err := xlsx.SaveAs("calendar.xlsx"); err != nil { | |
log.Fatalf("%v\n", err) | |
} | |
println("ok") | |
} | |
// 背景色を変更する関数 --- (*10) | |
func setCellBackgroundColor(f *excelize.File, sheet, cell1, cell2, color string) { | |
// 既存のスタイルを取得 | |
styleId, _ := f.GetCellStyle(sheet, cell1) | |
style, _ := f.GetStyle(styleId) | |
// 背景色を変更 | |
style.Fill.Color = []string{color} | |
// 新しいスタイルを作成 | |
newStyleID, _ := f.NewStyle(style) | |
// 新しいスタイルをセルに適用 | |
if err := f.SetCellStyle(sheet, cell1, cell2, newStyleID); err != nil { | |
log.Printf("スタイルの適用に失敗しました: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment