comment.go 10 KB

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