comment.go 10.2 KB
Newer Older
xurime's avatar
xurime 已提交
1
// Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
xurime's avatar
xurime 已提交
2 3 4 5
// this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
//
// Package excelize providing a set of functions that allow you to write to
xurime's avatar
xurime 已提交
6
// and read from XLSX / XLSM / XLTM files. Supports reading and writing
xurime's avatar
xurime 已提交
7
// spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
xurime's avatar
xurime 已提交
8 9
// complex components by high compatibility, and provided streaming API for
// generating or reading data from a worksheet with huge amounts of data. This
10
// library needs Go version 1.15 or later.
xurime's avatar
xurime 已提交
11

12 13 14
package excelize

import (
15
	"bytes"
16 17
	"encoding/json"
	"encoding/xml"
R
Rad Cirskis 已提交
18
	"fmt"
19 20
	"io"
	"log"
21
	"path/filepath"
22 23 24 25
	"strconv"
	"strings"
)

xurime's avatar
xurime 已提交
26 27
// parseFormatCommentsSet provides a function to parse the format settings of
// the comment with default value.
28
func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
29 30 31 32
	format := formatComment{
		Author: "Author:",
		Text:   " ",
	}
33
	err := json.Unmarshal([]byte(formatSet), &format)
34
	return &format, err
35 36
}

xurime's avatar
xurime 已提交
37 38
// GetComments retrieves all comments and returns a map of worksheet name to
// the worksheet comments.
39 40
func (f *File) GetComments() (comments map[string][]Comment) {
	comments = map[string][]Comment{}
41 42
	for n, path := range f.sheetMap {
		if d := f.commentsReader("xl" + strings.TrimPrefix(f.getSheetComments(filepath.Base(path)), "..")); d != nil {
43 44 45 46 47 48 49 50
			sheetComments := []Comment{}
			for _, comment := range d.CommentList.Comment {
				sheetComment := Comment{}
				if comment.AuthorID < len(d.Authors) {
					sheetComment.Author = d.Authors[comment.AuthorID].Author
				}
				sheetComment.Ref = comment.Ref
				sheetComment.AuthorID = comment.AuthorID
xurime's avatar
xurime 已提交
51 52 53
				if comment.Text.T != nil {
					sheetComment.Text += *comment.Text.T
				}
54
				for _, text := range comment.Text.R {
xurime's avatar
xurime 已提交
55 56 57
					if text.T != nil {
						sheetComment.Text += text.T.Val
					}
58 59 60 61
				}
				sheetComments = append(sheetComments, sheetComment)
			}
			comments[n] = sheetComments
62 63 64 65 66
		}
	}
	return
}

67
// getSheetComments provides the method to get the target comment reference by
68 69 70
// given worksheet file path.
func (f *File) getSheetComments(sheetFile string) string {
	var rels = "xl/worksheets/_rels/" + sheetFile + ".rels"
xurime's avatar
xurime 已提交
71
	if sheetRels := f.relsReader(rels); sheetRels != nil {
72 73 74 75
		for _, v := range sheetRels.Relationships {
			if v.Type == SourceRelationshipComments {
				return v.Target
			}
76 77 78 79 80
		}
	}
	return ""
}

81
// AddComment provides the method to add comment in a sheet by given worksheet
82 83
// index, cell and format set (such as author and text). Note that the max
// author length is 255 and the max text length is 32512. For example, add a
84 85
// comment in Sheet1!$A$30:
//
86
//    err := f.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
87
//
88 89 90 91 92
func (f *File) AddComment(sheet, cell, format string) error {
	formatSet, err := parseFormatCommentsSet(format)
	if err != nil {
		return err
	}
93
	// Read sheet data.
94
	ws, err := f.workSheetReader(sheet)
xurime's avatar
xurime 已提交
95 96 97
	if err != nil {
		return err
	}
98 99 100 101
	commentID := f.countComments() + 1
	drawingVML := "xl/drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
	sheetRelationshipsComments := "../comments" + strconv.Itoa(commentID) + ".xml"
	sheetRelationshipsDrawingVML := "../drawings/vmlDrawing" + strconv.Itoa(commentID) + ".vml"
102
	if ws.LegacyDrawing != nil {
103
		// The worksheet already has a comments relationships, use the relationships drawing ../drawings/vmlDrawing%d.vml.
104
		sheetRelationshipsDrawingVML = f.getSheetRelationshipsTargetByID(sheet, ws.LegacyDrawing.RID)
105 106 107 108
		commentID, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(sheetRelationshipsDrawingVML, "../drawings/vmlDrawing"), ".vml"))
		drawingVML = strings.Replace(sheetRelationshipsDrawingVML, "..", "xl", -1)
	} else {
		// Add first comment for given sheet.
109
		sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(f.sheetMap[trimSheetName(sheet)], "xl/worksheets/") + ".rels"
xurime's avatar
xurime 已提交
110 111
		rID := f.addRels(sheetRels, SourceRelationshipDrawingVML, sheetRelationshipsDrawingVML, "")
		f.addRels(sheetRels, SourceRelationshipComments, sheetRelationshipsComments, "")
112
		f.addSheetNameSpace(sheet, SourceRelationship)
113 114 115
		f.addSheetLegacyDrawing(sheet, rID)
	}
	commentsXML := "xl/comments" + strconv.Itoa(commentID) + ".xml"
R
Rad Cirskis 已提交
116 117 118 119 120 121 122 123 124
	var colCount int
	for i, l := range strings.Split(formatSet.Text, "\n") {
		if ll := len(l); ll > colCount {
			if i == 0 {
				ll += len(formatSet.Author)
			}
			colCount = ll
		}
	}
125 126 127 128
	err = f.addDrawingVML(commentID, drawingVML, cell, strings.Count(formatSet.Text, "\n")+1, colCount)
	if err != nil {
		return err
	}
129
	f.addComment(commentsXML, cell, formatSet)
xurime's avatar
xurime 已提交
130
	f.addContentTypePart(commentID, "comments")
131
	return err
132 133
}

xurime's avatar
xurime 已提交
134
// addDrawingVML provides a function to create comment as
135
// xl/drawings/vmlDrawing%d.vml by given commit ID and cell.
136 137 138 139 140
func (f *File) addDrawingVML(commentID int, drawingVML, cell string, lineCount, colCount int) error {
	col, row, err := CellNameToCoordinates(cell)
	if err != nil {
		return err
	}
141
	yAxis := col - 1
142
	xAxis := row - 1
143 144 145 146 147 148 149 150 151 152 153 154 155
	vml := f.VMLDrawing[drawingVML]
	if vml == nil {
		vml = &vmlDrawing{
			XMLNSv:  "urn:schemas-microsoft-com:vml",
			XMLNSo:  "urn:schemas-microsoft-com:office:office",
			XMLNSx:  "urn:schemas-microsoft-com:office:excel",
			XMLNSmv: "http://macVmlSchemaUri",
			Shapelayout: &xlsxShapelayout{
				Ext: "edit",
				IDmap: &xlsxIDmap{
					Ext:  "edit",
					Data: commentID,
				},
156
			},
157 158 159 160 161 162 163 164 165 166
			Shapetype: &xlsxShapetype{
				ID:        "_x0000_t202",
				Coordsize: "21600,21600",
				Spt:       202,
				Path:      "m0,0l0,21600,21600,21600,21600,0xe",
				Stroke: &xlsxStroke{
					Joinstyle: "miter",
				},
				VPath: &vPath{
					Gradientshapeok: "t",
167
					Connecttype:     "rect",
168
				},
169
			},
170
		}
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
	}
	sp := encodeShape{
		Fill: &vFill{
			Color2: "#fbfe82",
			Angle:  -180,
			Type:   "gradient",
			Fill: &oFill{
				Ext:  "view",
				Type: "gradientUnscaled",
			},
		},
		Shadow: &vShadow{
			On:       "t",
			Color:    "black",
			Obscured: "t",
		},
		Path: &vPath{
			Connecttype: "none",
		},
		Textbox: &vTextbox{
			Style: "mso-direction-alt:auto",
			Div: &xlsxDiv{
				Style: "text-align:left",
			},
		},
		ClientData: &xClientData{
			ObjectType: "Note",
R
Rad Cirskis 已提交
198 199
			Anchor: fmt.Sprintf(
				"%d, 23, %d, 0, %d, %d, %d, 5",
xurime's avatar
xurime 已提交
200
				1+yAxis, 1+xAxis, 2+yAxis+lineCount, colCount+yAxis, 2+xAxis+lineCount),
R
Rad Cirskis 已提交
201 202 203
			AutoFill: "True",
			Row:      xAxis,
			Column:   yAxis,
204 205 206 207 208 209 210 211 212 213 214
		},
	}
	s, _ := xml.Marshal(sp)
	shape := xlsxShape{
		ID:          "_x0000_s1025",
		Type:        "#_x0000_t202",
		Style:       "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
		Fillcolor:   "#fbf6d6",
		Strokecolor: "#edeaa1",
		Val:         string(s[13 : len(s)-14]),
	}
215 216
	d := f.decodeVMLDrawingReader(drawingVML)
	if d != nil {
217 218 219 220 221 222 223 224 225 226 227 228 229
		for _, v := range d.Shape {
			s := xlsxShape{
				ID:          "_x0000_s1025",
				Type:        "#_x0000_t202",
				Style:       "position:absolute;73.5pt;width:108pt;height:59.25pt;z-index:1;visibility:hidden",
				Fillcolor:   "#fbf6d6",
				Strokecolor: "#edeaa1",
				Val:         v.Val,
			}
			vml.Shape = append(vml.Shape, s)
		}
	}
	vml.Shape = append(vml.Shape, shape)
230
	f.VMLDrawing[drawingVML] = vml
231
	return err
232 233
}

xurime's avatar
xurime 已提交
234 235
// addComment provides a function to create chart as xl/comments%d.xml by
// given cell and format sets.
236
func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
237 238 239 240 241 242 243 244
	a := formatSet.Author
	t := formatSet.Text
	if len(a) > 255 {
		a = a[0:255]
	}
	if len(t) > 32512 {
		t = t[0:32512]
	}
245 246 247 248 249 250 251
	comments := f.commentsReader(commentsXML)
	if comments == nil {
		comments = &xlsxComments{
			Authors: []xlsxAuthor{
				{
					Author: formatSet.Author,
				},
252
			},
253
		}
254
	}
255
	defaultFont := f.GetDefaultFont()
256
	bold := ""
257 258 259 260 261
	cmt := xlsxComment{
		Ref:      cell,
		AuthorID: 0,
		Text: xlsxText{
			R: []xlsxR{
262
				{
263
					RPr: &xlsxRPr{
264
						B:  &bold,
265
						Sz: &attrValFloat{Val: float64Ptr(9)},
266 267 268
						Color: &xlsxColor{
							Indexed: 81,
						},
269 270
						RFont:  &attrValString{Val: stringPtr(defaultFont)},
						Family: &attrValInt{Val: intPtr(2)},
271
					},
xurime's avatar
xurime 已提交
272
					T: &xlsxT{Val: a},
273
				},
274
				{
275
					RPr: &xlsxRPr{
276
						Sz: &attrValFloat{Val: float64Ptr(9)},
277 278 279
						Color: &xlsxColor{
							Indexed: 81,
						},
280 281
						RFont:  &attrValString{Val: stringPtr(defaultFont)},
						Family: &attrValInt{Val: intPtr(2)},
282
					},
xurime's avatar
xurime 已提交
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
}

xurime's avatar
xurime 已提交
292 293
// countComments provides a function to get comments files count storage in
// the folder xl.
294
func (f *File) countComments() int {
295
	c1, c2 := 0, 0
296 297
	for k := range f.XLSX {
		if strings.Contains(k, "xl/comments") {
298
			c1++
299 300
		}
	}
301 302 303 304 305 306 307 308 309
	for rel := range f.Comments {
		if strings.Contains(rel, "xl/comments") {
			c2++
		}
	}
	if c1 < c2 {
		return c2
	}
	return c1
310
}
311 312 313 314

// decodeVMLDrawingReader provides a function to get the pointer to the
// structure after deserialization of xl/drawings/vmlDrawing%d.xml.
func (f *File) decodeVMLDrawingReader(path string) *decodeVmlDrawing {
315 316
	var err error

317 318 319
	if f.DecodeVMLDrawing[path] == nil {
		c, ok := f.XLSX[path]
		if ok {
320 321 322 323 324
			f.DecodeVMLDrawing[path] = new(decodeVmlDrawing)
			if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(c))).
				Decode(f.DecodeVMLDrawing[path]); err != nil && err != io.EOF {
				log.Printf("xml decode error: %s", err)
			}
325 326 327 328 329
		}
	}
	return f.DecodeVMLDrawing[path]
}

330
// vmlDrawingWriter provides a function to save xl/drawings/vmlDrawing%d.xml
331 332 333 334 335 336 337 338 339 340 341 342 343
// after serialize structure.
func (f *File) vmlDrawingWriter() {
	for path, vml := range f.VMLDrawing {
		if vml != nil {
			v, _ := xml.Marshal(vml)
			f.XLSX[path] = v
		}
	}
}

// commentsReader provides a function to get the pointer to the structure
// after deserialization of xl/comments%d.xml.
func (f *File) commentsReader(path string) *xlsxComments {
344 345
	var err error

346 347 348
	if f.Comments[path] == nil {
		content, ok := f.XLSX[path]
		if ok {
349 350 351 352 353
			f.Comments[path] = new(xlsxComments)
			if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(content))).
				Decode(f.Comments[path]); err != nil && err != io.EOF {
				log.Printf("xml decode error: %s", err)
			}
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
		}
	}
	return f.Comments[path]
}

// commentsWriter provides a function to save xl/comments%d.xml after
// serialize structure.
func (f *File) commentsWriter() {
	for path, c := range f.Comments {
		if c != nil {
			v, _ := xml.Marshal(c)
			f.saveFileList(path, v)
		}
	}
}