col.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package excelize
  2. import (
  3. "encoding/xml"
  4. "strings"
  5. )
  6. // SetColWidth provides function to set the width of a single column or multiple
  7. // columns. For example:
  8. //
  9. // xlsx := excelize.CreateFile()
  10. // xlsx.SetColWidth("Sheet1", "A", "H", 20)
  11. // err := xlsx.Save()
  12. // if err != nil {
  13. // fmt.Println(err)
  14. // os.Exit(1)
  15. // }
  16. //
  17. func (f *File) SetColWidth(sheet, startcol, endcol string, width float64) {
  18. min := titleToNumber(strings.ToUpper(startcol)) + 1
  19. max := titleToNumber(strings.ToUpper(endcol)) + 1
  20. if min > max {
  21. min, max = max, min
  22. }
  23. var xlsx xlsxWorksheet
  24. name := "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  25. xml.Unmarshal([]byte(f.readXML(name)), &xlsx)
  26. col := xlsxCol{
  27. Min: min,
  28. Max: max,
  29. Width: width,
  30. CustomWidth: true,
  31. }
  32. if xlsx.Cols != nil {
  33. xlsx.Cols.Col = append(xlsx.Cols.Col, col)
  34. } else {
  35. cols := xlsxCols{}
  36. cols.Col = append(cols.Col, col)
  37. xlsx.Cols = &cols
  38. }
  39. output, _ := xml.Marshal(xlsx)
  40. f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  41. }