瀏覽代碼

修改Excel列名生成函数

yjp 6 月之前
父節點
當前提交
c74eecca5b
共有 2 個文件被更改,包括 60 次插入2 次删除
  1. 45 2
      excelutils/excelutils.go
  2. 15 0
      excelutils/excelutils_test.go

+ 45 - 2
excelutils/excelutils.go

@@ -3,7 +3,7 @@ package excelutils
 import (
 	"bytes"
 	"fmt"
-	"git.sxidc.com/go-tools/utils/strutils"
+	"github.com/pkg/errors"
 	"github.com/xuri/excelize/v2"
 	"log"
 	"reflect"
@@ -52,7 +52,12 @@ func ExportExcel(titleList []string, data []interface{}, sheetName string) ([]by
 	}
 
 	length := len(titleList)
-	headStyle := strutils.GenerateUpperLetters(length)
+
+	headStyle, err := generateExcelColumnIndexes(length)
+	if err != nil {
+		return nil, err
+	}
+
 	var lastRow string
 	var widthRow string
 	for k, v := range headStyle {
@@ -94,3 +99,41 @@ func ExportExcel(titleList []string, data []interface{}, sheetName string) ([]by
 
 	return buffer.Bytes(), nil
 }
+
+func generateExcelColumnIndexes(columnNum int) ([]string, error) {
+	if columnNum > 26*27 {
+		return nil, errors.New("columnNum is too large")
+	}
+
+	indexes := make([]string, 0)
+
+	for currentColumn := 1; currentColumn <= columnNum; currentColumn++ {
+		var index string
+
+		if currentColumn%26 == 0 {
+			index = "Z"
+		} else {
+			index = string(rune('A' + currentColumn%26 - 1))
+		}
+
+		if currentColumn <= 26 {
+			indexes = append(indexes, index)
+			continue
+		}
+
+		upperLetterIndex := currentColumn / 26
+		if upperLetterIndex%26 == 0 && currentColumn != 26*26 {
+			index = "Z" + index
+		} else {
+			if currentColumn%26 == 0 {
+				index = string(rune('A'+upperLetterIndex-2)) + "Z"
+			} else {
+				index = string(rune('A'+upperLetterIndex%26-1)) + index
+			}
+		}
+
+		indexes = append(indexes, index)
+	}
+
+	return indexes, nil
+}

+ 15 - 0
excelutils/excelutils_test.go

@@ -0,0 +1,15 @@
+package excelutils
+
+import (
+	"fmt"
+	"testing"
+)
+
+func TestGenerate(t *testing.T) {
+	fmt.Println(generateExcelColumnIndexes(1))
+	fmt.Println(generateExcelColumnIndexes(26))
+	fmt.Println(generateExcelColumnIndexes(27))
+	fmt.Println(generateExcelColumnIndexes(52))
+	fmt.Println(generateExcelColumnIndexes(53))
+	fmt.Println(generateExcelColumnIndexes(26 * 27))
+}