Go언어 golang
고랭 엑셀 - golang excel #2 스타일 기본
미래의 고
2023. 3. 5. 22:09
이전 글에 기본 출력만으로는 'CSV' 파일 출력으로도 충분히 되는 문제입니다.
현업에선 보고가 될 수 있는 수준으로 스타일을 반영해야만 합니다.
그래서 이번 글에서는 기본적인 폰트 정렬/스타일, 셀 넓이 조정, 셀 라인 설정 정도 추가 해 보겠습니다.
출력물은 다음과 같습니다.
package main
import (
"fmt"
"github.com/xuri/excelize/v2"
"time"
)
func genMockData() [][]string {
//시간, 사용처, 금액, 비고
return [][]string{
{"2023-03-04 11:66", "하늘나라", "12000", "신용카드"},
{"2023-03-03 11:66", "우리나라", "8000", "체크카드"},
{"2023-03-02 11:66", "재미나라", "7000", "현금"},
{"2023-03-01 11:66", "김밥나라", "13000", "신용카드"},
}
}
func getCellStyle(f *excelize.File, style string) int {
switch style {
case "header":
style, err := f.NewStyle(&excelize.Style{
Font: &excelize.Font{Bold: true, Size: 16},
Alignment: &excelize.Alignment{Horizontal: "center"},
Border: []excelize.Border{
{Type: "left", Color: "000000", Style: 1},
{Type: "top", Color: "000001", Style: 1},
{Type: "bottom", Color: "000000", Style: 2}, // 2 굵은 선
{Type: "right", Color: "000000", Style: 1},
},
Fill: excelize.Fill{Type: "pattern", Color: []string{"999999"}, Pattern: 1},
})
if err != nil {
panic(err)
}
return style
default:
style, err := f.NewStyle(&excelize.Style{
Border: []excelize.Border{
{Type: "left", Color: "000000", Style: 1},
{Type: "top", Color: "000000", Style: 1},
{Type: "bottom", Color: "000000", Style: 1},
{Type: "right", Color: "000000", Style: 1},
},
Fill: excelize.Fill{Type: "pattern", Color: []string{"CCCC99"}, Pattern: 1},
})
if err != nil {
panic(err)
}
return style
}
}
func main() {
f := excelize.NewFile()
sheetName := "ex1"
sheet, err := f.NewSheet(sheetName)
if err != nil {
fmt.Println(err)
return
}
f.SetColWidth(sheetName, "A", "A", 20) // 시간 컬럼 넓이
f.SetColWidth(sheetName, "B", "D", 15) // 사용처, 금액, 비고 컬럼 넓이
styleDefault := getCellStyle(f, "")
styleHeader := getCellStyle(f, "header")
rs := genMockData()
// print header
f.SetCellValue(sheetName, "A1", "시간")
f.SetCellValue(sheetName, "B1", "사용처")
f.SetCellValue(sheetName, "C1", "금액")
f.SetCellValue(sheetName, "D1", "비고")
f.SetCellStyle(sheetName, "A1", "D1", styleHeader)
// print data
for i, row := range rs {
f.SetCellValue(sheetName, fmt.Sprintf("A%d", i+2), row[0])
f.SetCellValue(sheetName, fmt.Sprintf("B%d", i+2), row[1])
f.SetCellValue(sheetName, fmt.Sprintf("C%d", i+2), row[2])
f.SetCellValue(sheetName, fmt.Sprintf("D%d", i+2), row[3])
f.SetCellStyle(sheetName, fmt.Sprintf("A%d", i+2), fmt.Sprintf("D%d", i+2), styleDefault)
}
filename := fmt.Sprintf("%s.xlsx", time.Now().Format("2006-01-02-1504"))
f.SetActiveSheet(sheet)
if err := f.SaveAs(filename); err != nil {
fmt.Println(err)
}
fmt.Println("생성 완료")
}