From 13409e141fadd8a1f5a682e092f881ac1e0f5317 Mon Sep 17 00:00:00 2001 From: gazebo Date: Tue, 16 Jul 2019 18:44:48 +0800 Subject: [PATCH] - colWithList in Obj2Excel --- business/jxutils/excel/excel.go | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/business/jxutils/excel/excel.go b/business/jxutils/excel/excel.go index 217a4493f..ff991a88d 100644 --- a/business/jxutils/excel/excel.go +++ b/business/jxutils/excel/excel.go @@ -46,10 +46,14 @@ func Obj2Excel(sheetList []*Obj2ExcelSheetConfig) []byte { excelFile.NewSheet(sheetConfig.Title) } isMemberStruct := typeInfo.Kind() == reflect.Struct + colWithList := make([]float64, len(sheetConfig.CaptionList)) if isMemberStruct { var indexSlice [][]int name2IndexMap := utils.GetStructNameIndex(typeInfo, "json") for col, name := range sheetConfig.CaptionList { + if colWith := float64(len(name)); colWith > colWithList[col] { + colWithList[col] = colWith + } if _, ok := name2IndexMap[name]; !ok { panic(fmt.Sprintf("col:%s不能找到相应的数据", name)) } @@ -58,7 +62,11 @@ func Obj2Excel(sheetList []*Obj2ExcelSheetConfig) []byte { } for i := 0; i < valueInfo.Len(); i++ { for col, index := range indexSlice { - excelFile.SetCellStr(sheetConfig.Title, genAxis(i+1, col), fmt.Sprint(reflect.Indirect(valueInfo.Index(i)).FieldByIndex(index).Interface())) + str := fmt.Sprint(reflect.Indirect(valueInfo.Index(i)).FieldByIndex(index).Interface()) + // if colWith := float64(len(str)); colWith > colWithList[col] { + // colWithList[col] = colWith + // } + excelFile.SetCellStr(sheetConfig.Title, genAxis(i+1, col), str) } } } else { @@ -71,6 +79,9 @@ func Obj2Excel(sheetList []*Obj2ExcelSheetConfig) []byte { } } for col, name := range sheetConfig.CaptionList { + if colWith := float64(len(name)); colWith > colWithList[col] { + colWithList[col] = colWith + } if name2IndexMap != nil { if _, ok := name2IndexMap[name]; !ok { panic(fmt.Sprintf("col:%s不能找到相应的数据", name)) @@ -81,10 +92,18 @@ func Obj2Excel(sheetList []*Obj2ExcelSheetConfig) []byte { for i := 0; i < valueInfo.Len(); i++ { mapData := valueInfo.Index(i).Interface().(map[string]interface{}) for col, name := range sheetConfig.CaptionList { - excelFile.SetCellStr(sheetConfig.Title, genAxis(i+1, col), fmt.Sprint(mapData[name])) + str := fmt.Sprint(mapData[name]) + // if colWith := float64(len(str)); colWith > colWithList[col] { + // colWithList[col] = colWith + // } + excelFile.SetCellStr(sheetConfig.Title, genAxis(i+1, col), str) } } } + // for col := range sheetConfig.CaptionList { + // colName, _ := excelize.ColumnNumberToName(col + 1) + // excelFile.SetColWidth(sheetConfig.Title, colName, colName, colWithList[col]) + // } } buf := &bytes.Buffer{} excelFile.Write(buf)