excel.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Copyright (c) [2022] [程凯 [email protected]]
  2. // [ohUrlShortener] is licensed under Mulan PSL v2.
  3. // You can use this software according to the terms and conditions of the Mulan PSL v2.
  4. // You may obtain a copy of Mulan PSL v2 at:
  5. // http://license.coscl.org.cn/MulanPSL2
  6. // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
  7. // See the Mulan PSL v2 for more details.
  8. package export
  9. import (
  10. "errors"
  11. "strconv"
  12. "ohurlshortener/core"
  13. "github.com/xuri/excelize/v2"
  14. )
  15. func AccessLogToExcel(logs []core.AccessLog) ([]byte, error) {
  16. if logs == nil {
  17. return nil, errors.New("数据为空")
  18. }
  19. f := excelize.NewFile()
  20. index := f.NewSheet("Sheet1")
  21. // 填充表头
  22. f.SetCellValue("Sheet1", "A1", "短链接")
  23. f.SetCellValue("Sheet1", "B1", "访问时间")
  24. f.SetCellValue("Sheet1", "C1", "访问IP")
  25. f.SetCellValue("Sheet1", "D1", "UserAgent")
  26. for i := 0; i < len(logs); i++ {
  27. f.SetCellValue("Sheet1", "A"+strconv.Itoa(i+2), logs[i].ShortUrl)
  28. f.SetCellValue("Sheet1", "B"+strconv.Itoa(i+2), logs[i].AccessTime)
  29. f.SetCellValue("Sheet1", "C"+strconv.Itoa(i+2), logs[i].Ip.String)
  30. f.SetCellValue("Sheet1", "D"+strconv.Itoa(i+2), logs[i].UserAgent.String)
  31. }
  32. f.SetActiveSheet(index)
  33. if excellBytes, erorrW := f.WriteToBuffer(); erorrW != nil {
  34. return nil, erorrW
  35. } else {
  36. return excellBytes.Bytes(), nil
  37. }
  38. }