package export import ( "fmt" "github.com/xuri/excelize/v2" ) type Cell struct { Value any // 标题位置(列) Location Location // 标题合并列数 Colspan int // 标题合并行数 Rowspan int Style *excelize.Style } type CellLocation struct { LeftX int RightX int TopY int BottomY int IsMerge bool } func (e *Exporter) SetCell(sheet string, cell Cell) { start_col, end_col := e.CaculateCell(cell.Location, cell.Rowspan, cell.Colspan) if start_col != end_col { e.xlsx.MergeCell(sheet, start_col, end_col) } leftx, topy, _ := excelize.CellNameToCoordinates(start_col) rightx, bottomy, _ := excelize.CellNameToCoordinates(end_col) e.xlsx.SetCellValue(sheet, start_col, cell.Value) CellLocation := CellLocation{ LeftX: leftx, RightX: rightx, TopY: topy, BottomY: bottomy, IsMerge: start_col != end_col, } // 记录当前单元格位置 e.preLocation = &CellLocation if cell.Style != nil { style, _ := e.xlsx.NewStyle(cell.Style) e.xlsx.SetCellStyle(sheet, start_col, end_col, style) } else if e.GlobalCellStyle != nil { style, _ := e.xlsx.NewStyle(e.GlobalCellStyle) e.xlsx.SetCellStyle(sheet, start_col, end_col, style) } } func (e *Exporter) CaculateCell(location Location, rowSpan, colSpan int) (string, string) { if rowSpan >= 1 { rowSpan -= 1 } else { rowSpan = 0 } if colSpan >= 1 { colSpan -= 1 } else { colSpan = 0 } col_name, _ := excelize.ColumnNumberToName(location.X) start_col := fmt.Sprintf("%s%d", col_name, location.Y) h_pos, _ := excelize.ColumnNumberToName(location.X + colSpan) end_col := fmt.Sprintf("%s%d", h_pos, location.Y+rowSpan) return start_col, end_col }