comment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. // Copyright 2016 - 2023 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to and
  6. // read from XLAM / XLSM / XLSX / XLTM / XLTX files. Supports reading and
  7. // writing spreadsheet documents generated by Microsoft Excel™ 2007 and later.
  8. // Supports complex components by high compatibility, and provided streaming
  9. // API for generating or reading data from a worksheet with huge amounts of
  10. // data. This library needs Go version 1.16 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/xml"
  15. "fmt"
  16. "io"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. )
  21. // GetComments retrieves all comments in a worksheet by given worksheet name.
  22. func (f *File) GetComments(sheet string) ([]Comment, error) {
  23. var comments []Comment
  24. sheetXMLPath, ok := f.getSheetXMLPath(sheet)
  25. if !ok {
  26. return comments, newNoExistSheetError(sheet)
  27. }
  28. commentsXML := f.getSheetComments(filepath.Base(sheetXMLPath))
  29. if !strings.HasPrefix(commentsXML, "/") {
  30. commentsXML = "xl" + strings.TrimPrefix(commentsXML, "..")
  31. }
  32. commentsXML = strings.TrimPrefix(commentsXML, "/")
  33. cmts, err := f.commentsReader(commentsXML)
  34. if err != nil {
  35. return comments, err
  36. }
  37. if cmts != nil {
  38. for _, cmt := range cmts.CommentList.Comment {
  39. comment := Comment{}
  40. if cmt.AuthorID < len(cmts.Authors.Author) {
  41. comment.Author = cmts.Authors.Author[cmt.AuthorID]
  42. }
  43. comment.Cell = cmt.Ref
  44. comment.AuthorID = cmt.AuthorID
  45. if cmt.Text.T != nil {
  46. comment.Text += *cmt.Text.T
  47. }
  48. for _, text := range cmt.Text.R {
  49. if text.T != nil {
  50. run := RichTextRun{Text: text.T.Val}
  51. if text.RPr != nil {
  52. run.Font = newFont(text.RPr)
  53. }
  54. comment.Runs = append(comment.Runs, run)
  55. }
  56. }
  57. comments = append(comments, comment)
  58. }
  59. }
  60. return comments, nil
  61. }
  62. // getSheetComments provides the method to get the target comment reference by
  63. // given worksheet file path.
  64. func (f *File) getSheetComments(sheetFile string) string {
  65. rels, _ := f.relsReader("xl/worksheets/_rels/" + sheetFile + ".rels")
  66. if sheetRels := rels; sheetRels != nil {
  67. sheetRels.Lock()
  68. defer sheetRels.Unlock()
  69. for _, v := range sheetRels.Relationships {
  70. if v.Type == SourceRelationshipComments {
  71. return v.Target
  72. }
  73. }
  74. }
  75. return ""
  76. }
  77. // AddComment provides the method to add comment in a sheet by given worksheet
  78. // index, cell and format set (such as author and text). Note that the max
  79. // author length is 255 and the max text length is 32512. For example, add a
  80. // comment in Sheet1!$A$30:
  81. //
  82. // err := f.AddComment("Sheet1", excelize.Comment{
  83. // Cell: "A12",
  84. // Author: "Excelize",
  85. // Runs: []excelize.RichTextRun{
  86. // {Text: "Excelize: ", Font: &excelize.Font{Bold: true}},
  87. // {Text: "This is a comment."},
  88. // },
  89. // })
  90. func (f *File) AddComment(sheet string, comment Comment) error {
  91. // Read sheet data.
  92. ws, err := f.workSheetReader(sheet)
  93. if err != nil {
  94. return err
  95. }
  96. commentID := f.countComments() + 1
  97. drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  98. sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
  99. sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
  100. if ws.LegacyDrawing != nil {
  101. // The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
  102. sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, ws.LegacyDrawing.RID)
  103. commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
  104. drawingVML = strings.ReplaceAll(sheetRelationshipsDrawingVML, "..", "xl")
  105. } else {
  106. // Add first comment for given sheet.
  107. sheetXMLPath, _ := f.getSheetXMLPath(sheet)
  108. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetXMLPath, "xl/worksheets/") + ".rels"
  109. rID := f.addRels(sheetRels, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
  110. f.addRels(sheetRels, SourceRelationshipComments, sheetRelationshipsComments, "")
  111. f.addSheetNameSpace(sheet, SourceRelationship)
  112. f.addSheetLegacyDrawing(sheet, rID)
  113. }
  114. commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
  115. var rows, cols int
  116. for _, runs := range comment.Runs {
  117. for _, subStr := range strings.Split(runs.Text, "\n") {
  118. rows++
  119. if chars := len(subStr); chars > cols {
  120. cols = chars
  121. }
  122. }
  123. }
  124. if err = f.addDrawingVML(commentID, drawingVML, comment.Cell, rows+1, cols); err != nil {
  125. return err
  126. }
  127. if err = f.addComment(commentsXML, comment); err != nil {
  128. return err
  129. }
  130. return f.addContentTypePart(commentID, "comments")
  131. }
  132. // DeleteComment provides the method to delete comment in a sheet by given
  133. // worksheet name. For example, delete the comment in Sheet1!$A$30:
  134. //
  135. // err := f.DeleteComment("Sheet1", "A30")
  136. func (f *File) DeleteComment(sheet, cell string) error {
  137. if err := checkSheetName(sheet); err != nil {
  138. return err
  139. }
  140. sheetXMLPath, ok := f.getSheetXMLPath(sheet)
  141. if !ok {
  142. return newNoExistSheetError(sheet)
  143. }
  144. commentsXML := f.getSheetComments(filepath.Base(sheetXMLPath))
  145. if !strings.HasPrefix(commentsXML, "/") {
  146. commentsXML = "xl" + strings.TrimPrefix(commentsXML, "..")
  147. }
  148. commentsXML = strings.TrimPrefix(commentsXML, "/")
  149. cmts, err := f.commentsReader(commentsXML)
  150. if err != nil {
  151. return err
  152. }
  153. if cmts != nil {
  154. for i := 0; i < len(cmts.CommentList.Comment); i++ {
  155. cmt := cmts.CommentList.Comment[i]
  156. if cmt.Ref != cell {
  157. continue
  158. }
  159. if len(cmts.CommentList.Comment) > 1 {
  160. cmts.CommentList.Comment = append(
  161. cmts.CommentList.Comment[:i],
  162. cmts.CommentList.Comment[i+1:]...,
  163. )
  164. i--
  165. continue
  166. }
  167. cmts.CommentList.Comment = nil
  168. }
  169. f.Comments[commentsXML] = cmts
  170. }
  171. return err
  172. }
  173. // addDrawingVML provides a function to create comment as
  174. // xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
  175. func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) error {
  176. col, row, err := CellNameToCoordinates(cell)
  177. if err != nil {
  178. return err
  179. }
  180. yAxis := col - 1
  181. xAxis := row - 1
  182. vml := f.VMLDrawing[drawingVML]
  183. if vml == nil {
  184. vml = &vmlDrawing{
  185. XMLNSv: "urn:schemas-microsoft-com:vml",
  186. XMLNSo: "urn:schemas-microsoft-com:office:office",
  187. XMLNSx: "urn:schemas-microsoft-com:office:excel",
  188. XMLNSmv: "http://macVmlSchemaUri",
  189. Shapelayout: &xlsxShapelayout{
  190. Ext: "edit",
  191. IDmap: &xlsxIDmap{
  192. Ext: "edit",
  193. Data: commentID,
  194. },
  195. },
  196. Shapetype: &xlsxShapetype{
  197. ID: "_x0000_t202",
  198. Coordsize: "21600,21600",
  199. Spt: 202,
  200. Path: "m0,0l0,21600,21600,21600,21600,0xe",
  201. Stroke: &xlsxStroke{
  202. Joinstyle: "miter",
  203. },
  204. VPath: &vPath{
  205. Gradientshapeok: "t",
  206. Connecttype: "rect",
  207. },
  208. },
  209. }
  210. // load exist comment shapes from xl/drawings/vmlDrawing%d.vml
  211. d, err := f.decodeVMLDrawingReader(drawingVML)
  212. if err != nil {
  213. return err
  214. }
  215. if d != nil {
  216. for _, v := range d.Shape {
  217. s := xlsxShape{
  218. ID: "_x0000_s1025",
  219. Type: "#_x0000_t202",
  220. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  221. Fillcolor: "#FBF6D6",
  222. Strokecolor: "#EDEAA1",
  223. Val: v.Val,
  224. }
  225. vml.Shape = append(vml.Shape, s)
  226. }
  227. }
  228. }
  229. sp := encodeShape{
  230. Fill: &vFill{
  231. Color2: "#FBFE82",
  232. Angle: -180,
  233. Type: "gradient",
  234. Fill: &oFill{
  235. Ext: "view",
  236. Type: "gradientUnscaled",
  237. },
  238. },
  239. Shadow: &vShadow{
  240. On: "t",
  241. Color: "black",
  242. Obscured: "t",
  243. },
  244. Path: &vPath{
  245. Connecttype: "none",
  246. },
  247. Textbox: &vTextbox{
  248. Style: "mso-direction-alt:auto",
  249. Div: &xlsxDiv{
  250. Style: "text-align:left",
  251. },
  252. },
  253. ClientData: &xClientData{
  254. ObjectType: "Note",
  255. Anchor: fmt.Sprintf(
  256. "%d, 23, %d, 0, %d, %d, %d, 5",
  257. 1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
  258. AutoFill: "True",
  259. Row: xAxis,
  260. Column: yAxis,
  261. },
  262. }
  263. s, _ := xml.Marshal(sp)
  264. shape := xlsxShape{
  265. ID: "_x0000_s1025",
  266. Type: "#_x0000_t202",
  267. Style: "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
  268. Fillcolor: "#FBF6D6",
  269. Strokecolor: "#EDEAA1",
  270. Val: string(s[13 : len(s)-14]),
  271. }
  272. vml.Shape = append(vml.Shape, shape)
  273. f.VMLDrawing[drawingVML] = vml
  274. return err
  275. }
  276. // addComment provides a function to create chart as xl/comments%d.xml by
  277. // given cell and format sets.
  278. func (f *File) addComment(commentsXML string, comment Comment) error {
  279. if comment.Author == "" {
  280. comment.Author = "Author"
  281. }
  282. if len(comment.Author) > MaxFieldLength {
  283. comment.Author = comment.Author[:MaxFieldLength]
  284. }
  285. cmts, err := f.commentsReader(commentsXML)
  286. if err != nil {
  287. return err
  288. }
  289. var authorID int
  290. if cmts == nil {
  291. cmts = &xlsxComments{Authors: xlsxAuthor{Author: []string{comment.Author}}}
  292. }
  293. if inStrSlice(cmts.Authors.Author, comment.Author, true) == -1 {
  294. cmts.Authors.Author = append(cmts.Authors.Author, comment.Author)
  295. authorID = len(cmts.Authors.Author) - 1
  296. }
  297. defaultFont, err := f.GetDefaultFont()
  298. if err != nil {
  299. return err
  300. }
  301. chars, cmt := 0, xlsxComment{
  302. Ref: comment.Cell,
  303. AuthorID: authorID,
  304. Text: xlsxText{R: []xlsxR{}},
  305. }
  306. if comment.Text != "" {
  307. if len(comment.Text) > TotalCellChars {
  308. comment.Text = comment.Text[:TotalCellChars]
  309. }
  310. cmt.Text.T = stringPtr(comment.Text)
  311. chars += len(comment.Text)
  312. }
  313. for _, run := range comment.Runs {
  314. if chars == TotalCellChars {
  315. break
  316. }
  317. if chars+len(run.Text) > TotalCellChars {
  318. run.Text = run.Text[:TotalCellChars-chars]
  319. }
  320. chars += len(run.Text)
  321. r := xlsxR{
  322. RPr: &xlsxRPr{
  323. Sz: &attrValFloat{Val: float64Ptr(9)},
  324. Color: &xlsxColor{
  325. Indexed: 81,
  326. },
  327. RFont: &attrValString{Val: stringPtr(defaultFont)},
  328. Family: &attrValInt{Val: intPtr(2)},
  329. },
  330. T: &xlsxT{Val: run.Text, Space: xml.Attr{
  331. Name: xml.Name{Space: NameSpaceXML, Local: "space"},
  332. Value: "preserve",
  333. }},
  334. }
  335. if run.Font != nil {
  336. r.RPr = newRpr(run.Font)
  337. }
  338. cmt.Text.R = append(cmt.Text.R, r)
  339. }
  340. cmts.CommentList.Comment = append(cmts.CommentList.Comment, cmt)
  341. f.Comments[commentsXML] = cmts
  342. return err
  343. }
  344. // countComments provides a function to get comments files count storage in
  345. // the folder xl.
  346. func (f *File) countComments() int {
  347. c1, c2 := 0, 0
  348. f.Pkg.Range(func(k, v interface{}) bool {
  349. if strings.Contains(k.(string), "xl/comments") {
  350. c1++
  351. }
  352. return true
  353. })
  354. for rel := range f.Comments {
  355. if strings.Contains(rel, "xl/comments") {
  356. c2++
  357. }
  358. }
  359. if c1 < c2 {
  360. return c2
  361. }
  362. return c1
  363. }
  364. // decodeVMLDrawingReader provides a function to get the pointer to the
  365. // structure after deserialization of xl/drawings/vmlDrawing%d.xml.
  366. func (f *File) decodeVMLDrawingReader(path string) (*decodeVmlDrawing, error) {
  367. if f.DecodeVMLDrawing[path] == nil {
  368. c, ok := f.Pkg.Load(path)
  369. if ok && c != nil {
  370. f.DecodeVMLDrawing[path] = new(decodeVmlDrawing)
  371. if err := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(c.([]byte)))).
  372. Decode(f.DecodeVMLDrawing[path]); err != nil && err != io.EOF {
  373. return nil, err
  374. }
  375. }
  376. }
  377. return f.DecodeVMLDrawing[path], nil
  378. }
  379. // vmlDrawingWriter provides a function to save xl/drawings/vmlDrawing%d.xml
  380. // after serialize structure.
  381. func (f *File) vmlDrawingWriter() {
  382. for path, vml := range f.VMLDrawing {
  383. if vml != nil {
  384. v, _ := xml.Marshal(vml)
  385. f.Pkg.Store(path, v)
  386. }
  387. }
  388. }
  389. // commentsReader provides a function to get the pointer to the structure
  390. // after deserialization of xl/comments%d.xml.
  391. func (f *File) commentsReader(path string) (*xlsxComments, error) {
  392. if f.Comments[path] == nil {
  393. content, ok := f.Pkg.Load(path)
  394. if ok && content != nil {
  395. f.Comments[path] = new(xlsxComments)
  396. if err := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(content.([]byte)))).
  397. Decode(f.Comments[path]); err != nil && err != io.EOF {
  398. return nil, err
  399. }
  400. }
  401. }
  402. return f.Comments[path], nil
  403. }
  404. // commentsWriter provides a function to save xl/comments%d.xml after
  405. // serialize structure.
  406. func (f *File) commentsWriter() {
  407. for path, c := range f.Comments {
  408. if c != nil {
  409. v, _ := xml.Marshal(c)
  410. f.saveFileList(path, v)
  411. }
  412. }
  413. }