设置富文本格式

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