excelutils.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package excelutils
  2. import (
  3. "bytes"
  4. "fmt"
  5. "git.sxidc.com/go-tools/utils/strutils"
  6. "github.com/xuri/excelize/v2"
  7. "log"
  8. "reflect"
  9. "strconv"
  10. )
  11. func ExportExcel(titleList []string, data []interface{}, sheetName string) ([]byte, error) {
  12. f := excelize.NewFile()
  13. defer func() {
  14. err := f.Close()
  15. if err != nil {
  16. log.Println("ExportExcel Close File:", err.Error())
  17. }
  18. }()
  19. err := f.SetSheetName("Sheet1", sheetName)
  20. if err != nil {
  21. return nil, err
  22. }
  23. header := make([]string, 0)
  24. for _, v := range titleList {
  25. header = append(header, v)
  26. }
  27. rowStyleID, _ := f.NewStyle(&excelize.Style{
  28. Font: &excelize.Font{
  29. Family: "arial",
  30. Size: 13,
  31. Color: "#666666",
  32. },
  33. Alignment: &excelize.Alignment{
  34. Horizontal: "center",
  35. Vertical: "center",
  36. },
  37. })
  38. err = f.SetSheetRow(sheetName, "A1", &header)
  39. if err != nil {
  40. return nil, err
  41. }
  42. err = f.SetRowHeight(sheetName, 1, 30)
  43. if err != nil {
  44. return nil, err
  45. }
  46. length := len(titleList)
  47. headStyle := strutils.GenerateUpperLetters(length)
  48. var lastRow string
  49. var widthRow string
  50. for k, v := range headStyle {
  51. if k == length-1 {
  52. lastRow = fmt.Sprintf("%s1", v)
  53. widthRow = v
  54. }
  55. }
  56. if err := f.SetColWidth(sheetName, "A", widthRow, 20); err != nil {
  57. return nil, err
  58. }
  59. rowNum := 1
  60. _ = f.SetCellStyle(sheetName, fmt.Sprintf("A%d", 1), fmt.Sprintf("%s", lastRow), rowStyleID)
  61. for _, v := range data {
  62. t := reflect.TypeOf(v)
  63. value := reflect.ValueOf(v)
  64. row := make([]interface{}, 0)
  65. for l := 0; l < t.NumField(); l++ {
  66. val := value.Field(l).Interface()
  67. row = append(row, val)
  68. }
  69. rowNum++
  70. err := f.SetSheetRow(sheetName, "A"+strconv.Itoa(rowNum), &row)
  71. if err != nil {
  72. return nil, err
  73. }
  74. }
  75. buffer := &bytes.Buffer{}
  76. err = f.Write(buffer)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return buffer.Bytes(), nil
  81. }