comment.go 11 KB

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