comment.go 11 KB

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