设置富文本格式

  1. func (f *File) SetCellRichText(sheet, cell string, runs []RichTextRun) error

根据给定的工作表、单元格坐标和富文本格式为指定单元格设置富文本。

例如,在名为 Sheet1 的工作表 A1 单元格设置富文本格式:

设置富文本格式

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/xuri/excelize/v2"
  5. )
  6. func main() {
  7. f := excelize.NewFile()
  8. defer func() {
  9. if err := f.Close(); err != nil {
  10. fmt.Println(err)
  11. }
  12. }()
  13. if err := f.SetRowHeight("Sheet1", 1, 35); err != nil {
  14. fmt.Println(err)
  15. return
  16. }
  17. if err := f.SetColWidth("Sheet1", "A", "A", 44); err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. if err := f.SetCellRichText("Sheet1", "A1", []excelize.RichTextRun{
  22. {
  23. Text: "bold",
  24. Font: &excelize.Font{
  25. Bold: true,
  26. Color: "2354E8",
  27. Family: "Times New Roman",
  28. },
  29. },
  30. {
  31. Text: " and ",
  32. Font: &excelize.Font{
  33. Family: "Times New Roman",
  34. },
  35. },
  36. {
  37. Text: "italic ",
  38. Font: &excelize.Font{
  39. Bold: true,
  40. Color: "E83723",
  41. Italic: true,
  42. Family: "Times New Roman",
  43. },
  44. },
  45. {
  46. Text: "text with color and font-family,",
  47. Font: &excelize.Font{
  48. Bold: true,
  49. Color: "2354E8",
  50. Family: "Times New Roman",
  51. },
  52. },
  53. {
  54. Text: "\r\nlarge text with ",
  55. Font: &excelize.Font{
  56. Size: 14,
  57. Color: "AD23E8",
  58. },
  59. },
  60. {
  61. Text: "strike",
  62. Font: &excelize.Font{
  63. Color: "E89923",
  64. Strike: true,
  65. },
  66. },
  67. {
  68. Text: " superscript",
  69. Font: &excelize.Font{
  70. Color: "DBC21F",
  71. VertAlign: "superscript",
  72. },
  73. },
  74. {
  75. Text: " and ",
  76. Font: &excelize.Font{
  77. Size: 14,
  78. Color: "AD23E8",
  79. VertAlign: "baseline",
  80. },
  81. },
  82. {
  83. Text: "underline",
  84. Font: &excelize.Font{
  85. Color: "23E833",
  86. Underline: "single",
  87. },
  88. },
  89. {
  90. Text: " subscript.",
  91. Font: &excelize.Font{
  92. Color: "017505",
  93. VertAlign: "subscript",
  94. },
  95. },
  96. }); err != nil {
  97. fmt.Println(err)
  98. return
  99. }
  100. style, err := f.NewStyle(&excelize.Style{
  101. Alignment: &excelize.Alignment{
  102. WrapText: true,
  103. },
  104. })
  105. if err != nil {
  106. fmt.Println(err)
  107. return
  108. }
  109. if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  110. fmt.Println(err)
  111. return
  112. }
  113. if err := f.SaveAs("Book1.xlsx"); err != nil {
  114. fmt.Println(err)
  115. }
  116. }