comment.go 10 KB

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