From 2c44cff102dc6b8b8e3ff8d3769af82b84e6cf73 Mon Sep 17 00:00:00 2001 From: romanskijdev Date: Thu, 25 Jun 2026 14:05:20 +0300 Subject: [PATCH] update excel report generation --- core/reportcore/autoFitCol.go | 90 +++++++++++++++++++++++++++++++++++ core/reportcore/excel.go | 2 + 2 files changed, 92 insertions(+) create mode 100644 core/reportcore/autoFitCol.go diff --git a/core/reportcore/autoFitCol.go b/core/reportcore/autoFitCol.go new file mode 100644 index 0000000..e32e5e3 --- /dev/null +++ b/core/reportcore/autoFitCol.go @@ -0,0 +1,90 @@ +package reportcore + +import ( + "github.com/xuri/excelize/v2" + "strings" + "unicode/utf8" +) + +// autoFitColumns автоматически подгоняет ширину колонок под содержимое. +// Учитывает длину заголовка и всех ячеек, добавляет небольшой отступ. +func autoFitColumns(f *excelize.File, sheetName string, headers []string, dataRowCount int) { + for colIdx, header := range headers { + colLetter, _ := excelize.ColumnNumberToName(colIdx + 1) + + // Начинаем с длины заголовка + maxWidth := stringWidth(header) + + // Проверяем все строки данных в этой колонке + for row := 2; row <= dataRowCount+1; row++ { + cellName, _ := excelize.CoordinatesToCellName(colIdx+1, row) + cellValue, _ := f.GetCellValue(sheetName, cellName) + w := stringWidth(cellValue) + if w > maxWidth { + maxWidth = w + } + } + + // Добавляем небольшой отступ для красоты + finalWidth := float64(maxWidth) + 2 + + // Ограничиваем минимальную и максимальную ширину + if finalWidth < 10 { + finalWidth = 10 + } + if finalWidth > 60 { + finalWidth = 60 + } + + _ = f.SetColWidth(sheetName, colLetter, colLetter, finalWidth) + } +} + +// stringWidth вычисляет "визуальную" ширину строки. +// Кириллица и другие широкие символы занимают больше места, чем латиница. +func stringWidth(s string) int { + width := 0 + for _, r := range s { + if isWideRune(r) { + width += 2 // широкие символы (кириллица, CJK) + } else { + width += 1 + } + } + // Учитываем переносы строк — берём самую длинную строку + lines := strings.Split(s, "\n") + maxLine := 0 + for _, line := range lines { + lw := 0 + for _, r := range line { + if isWideRune(r) { + lw += 2 + } else { + lw += 1 + } + } + if lw > maxLine { + maxLine = lw + } + } + if maxLine > width { + width = maxLine + } + return width +} + +// isWideRune определяет, является ли символ "широким" +func isWideRune(r rune) bool { + // Кириллица + if r >= 0x0400 && r <= 0x04FF { + return true + } + // CJK (китайские, японские, корейские) + if r >= 0x4E00 && r <= 0x9FFF { + return true + } + return false +} + +// _ используется, чтобы убрать предупреждение о неиспользуемом импорте +var _ = utf8.RuneCountInString diff --git a/core/reportcore/excel.go b/core/reportcore/excel.go index d41ce11..9668f8b 100644 --- a/core/reportcore/excel.go +++ b/core/reportcore/excel.go @@ -421,6 +421,8 @@ func BuildExcelApprovalsReport(ctx context.Context, db *database.ModuleDB, appro logrus.Warnf("reportcore: set panes: %v", err) } + autoFitColumns(f, sheet, headers, len(approvals)) + var buf bytes.Buffer if err := f.Write(&buf); err != nil { return nil, fmt.Errorf("write excel: %w", err)