设置富文本格式

  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: " and ",
  64. Font: &excelize.Font{
  65. Size: 14,
  66. Color: "ad23e8",
  67. },
  68. },
  69. {
  70. Text: "underline.",
  71. Font: &excelize.Font{
  72. Color: "23e833",
  73. Underline: "single",
  74. },
  75. },
  76. }); err != nil {
  77. fmt.Println(err)
  78. return
  79. }
  80. style, err := f.NewStyle(&excelize.Style{
  81. Alignment: &excelize.Alignment{
  82. WrapText: true,
  83. },
  84. })
  85. if err != nil {
  86. fmt.Println(err)
  87. return
  88. }
  89. if err := f.SetCellStyle("Sheet1", "A1", "A1", style); err != nil {
  90. fmt.Println(err)
  91. return
  92. }
  93. if err := f.SaveAs("Book1.xlsx"); err != nil {
  94. fmt.Println(err)
  95. }
  96. }