Skip to content

Commit

Permalink
- Add error return value for functions: AddChart(), AddComment(),…
Browse files Browse the repository at this point in the history
… `AddPicture()`, `AddShape()`, `AddTable()` and `SetConditionalFormat()`

- go test has been updated
  • Loading branch information
xuri committed May 27, 2018
1 parent aaced35 commit 9e463b4
Show file tree
Hide file tree
Showing 11 changed files with 117 additions and 72 deletions.
16 changes: 10 additions & 6 deletions chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ var (

// parseFormatChartSet provides function to parse the format settings of the
// chart with default value.
func parseFormatChartSet(formatSet string) *formatChart {
func parseFormatChartSet(formatSet string) (*formatChart, error) {
format := formatChart{
Dimension: formatChartDimension{
Width: 480,
Expand All @@ -216,8 +216,8 @@ func parseFormatChartSet(formatSet string) *formatChart {
},
ShowBlanksAs: "gap",
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}

// AddChart provides the method to add chart in a sheet by given chart format
Expand Down Expand Up @@ -357,8 +357,11 @@ func parseFormatChartSet(formatSet string) *formatChart {
//
// Set chart size by dimension property. The dimension property is optional. The default width is 480, and height is 290.
//
func (f *File) AddChart(sheet, cell, format string) {
formatSet := parseFormatChartSet(format)
func (f *File) AddChart(sheet, cell, format string) error {
formatSet, err := parseFormatChartSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
Expand All @@ -371,6 +374,7 @@ func (f *File) AddChart(sheet, cell, format string) {
f.addChart(formatSet)
f.addContentTypePart(chartID, "chart")
f.addContentTypePart(drawingID, "drawings")
return err
}

// countCharts provides function to get chart files count storage in the
Expand Down Expand Up @@ -1082,7 +1086,7 @@ func (f *File) drawingParser(drawingXML string, content *xlsxWsDr) int {
_, ok := f.XLSX[drawingXML]
if ok { // Append Model
decodeWsDr := decodeWsDr{}
xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
_ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
content.R = decodeWsDr.R
cNvPrID = len(decodeWsDr.OneCellAnchor) + len(decodeWsDr.TwoCellAnchor) + 1
for _, v := range decodeWsDr.OneCellAnchor {
Expand Down
18 changes: 11 additions & 7 deletions comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import (

// parseFormatCommentsSet provides function to parse the format settings of the
// comment with default value.
func parseFormatCommentsSet(formatSet string) *formatComment {
func parseFormatCommentsSet(formatSet string) (*formatComment, error) {
format := formatComment{
Author: "Author:",
Text: " ",
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}

// AddComment provides the method to add comment in a sheet by given worksheet
Expand All @@ -25,8 +25,11 @@ func parseFormatCommentsSet(formatSet string) *formatComment {
//
// xlsx.AddComment("Sheet1", "A30", `{"author":"Excelize: ","text":"This is a comment."}`)
//
func (f *File) AddComment(sheet, cell, format string) {
formatSet := parseFormatCommentsSet(format)
func (f *File) AddComment(sheet, cell, format string) error {
formatSet, err := parseFormatCommentsSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
commentID := f.countComments() + 1
Expand All @@ -48,6 +51,7 @@ func (f *File) AddComment(sheet, cell, format string) {
f.addComment(commentsXML, cell, formatSet)
f.addDrawingVML(commentID, drawingVML, cell)
f.addContentTypePart(commentID, "comments")
return err
}

// addDrawingVML provides function to create comment as
Expand Down Expand Up @@ -127,7 +131,7 @@ func (f *File) addDrawingVML(commentID int, drawingVML, cell string) {
c, ok := f.XLSX[drawingVML]
if ok {
d := decodeVmlDrawing{}
xml.Unmarshal([]byte(c), &d)
_ = xml.Unmarshal([]byte(c), &d)
for _, v := range d.Shape {
s := xlsxShape{
ID: "_x0000_s1025",
Expand Down Expand Up @@ -197,7 +201,7 @@ func (f *File) addComment(commentsXML, cell string, formatSet *formatComment) {
c, ok := f.XLSX[commentsXML]
if ok {
d := xlsxComments{}
xml.Unmarshal([]byte(c), &d)
_ = xml.Unmarshal([]byte(c), &d)
comments.CommentList.Comment = append(comments.CommentList.Comment, d.CommentList.Comment...)
}
comments.CommentList.Comment = append(comments.CommentList.Comment, cmt)
Expand Down
2 changes: 1 addition & 1 deletion excelize.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
}
if f.Sheet[name] == nil {
var xlsx xlsxWorksheet
xml.Unmarshal(f.readXML(name), &xlsx)
_ = xml.Unmarshal(f.readXML(name), &xlsx)
if f.checked == nil {
f.checked = make(map[string]bool)
}
Expand Down
28 changes: 24 additions & 4 deletions excelize_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,10 @@ func TestNewFile(t *testing.T) {
if err != nil {
t.Error(err)
}
// Test add picture to worksheet with invalid formatset
err = xlsx.AddPicture("Sheet1", "C2", "./test/images/excel.png", "")
if err != nil {
t.Error(err)
t.Log(err)
}
err = xlsx.SaveAs("./test/Book3.xlsx")
if err != nil {
Expand Down Expand Up @@ -651,6 +652,7 @@ func TestSetDeleteSheet(t *testing.T) {
t.Error(err)
}
xlsx.DeleteSheet("Sheet1")
xlsx.AddComment("Sheet1", "A1", "")
xlsx.AddComment("Sheet1", "A1", `{"author":"Excelize: ","text":"This is a comment."}`)
err = xlsx.SaveAs("./test/Book_delete_sheet.xlsx")
if err != nil {
Expand Down Expand Up @@ -765,9 +767,22 @@ func TestAddTable(t *testing.T) {
if err != nil {
t.Error(err)
}
xlsx.AddTable("Sheet1", "B26", "A21", ``)
xlsx.AddTable("Sheet2", "A2", "B5", `{"table_name":"table","table_style":"TableStyleMedium2", "show_first_column":true,"show_last_column":true,"show_row_stripes":false,"show_column_stripes":true}`)
xlsx.AddTable("Sheet2", "F1", "F1", `{"table_style":"TableStyleMedium8"}`)
err = xlsx.AddTable("Sheet1", "B26", "A21", `{}`)
if err != nil {
t.Error(err)
}
err = xlsx.AddTable("Sheet2", "A2", "B5", ``)
if err != nil {
t.Log(err)
}
err = xlsx.AddTable("Sheet2", "A2", "B5", `{"table_name":"table","table_style":"TableStyleMedium2", "show_first_column":true,"show_last_column":true,"show_row_stripes":false,"show_column_stripes":true}`)
if err != nil {
t.Error(err)
}
err = xlsx.AddTable("Sheet2", "F1", "F1", `{"table_style":"TableStyleMedium8"}`)
if err != nil {
t.Error(err)
}
err = xlsx.Save()
if err != nil {
t.Error(err)
Expand All @@ -783,6 +798,7 @@ func TestAddShape(t *testing.T) {
xlsx.AddShape("Sheet1", "B30", `{"type":"rect","paragraph":[{"text":"Rectangle"},{}]}`)
xlsx.AddShape("Sheet1", "C30", `{"type":"rect","paragraph":[]}`)
xlsx.AddShape("Sheet3", "H1", `{"type":"ellipseRibbon", "color":{"line":"#4286f4","fill":"#8eb9ff"}, "paragraph":[{"font":{"bold":true,"italic":true,"family":"Berlin Sans FB Demi","size":36,"color":"#777777","underline":"single"}}], "height": 90}`)
xlsx.AddShape("Sheet3", "H1", "")
err = xlsx.Save()
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -846,6 +862,7 @@ func TestAddChart(t *testing.T) {
for k, v := range values {
xlsx.SetCellValue("Sheet1", k, v)
}
xlsx.AddChart("Sheet1", "P1", "")
xlsx.AddChart("Sheet1", "P1", `{"type":"col","series":[{"name":"Sheet1!$A$30","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$30:$D$30"},{"name":"Sheet1!$A$31","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$31:$D$31"},{"name":"Sheet1!$A$32","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$32:$D$32"}],"format":{"x_scale":1.0,"y_scale":1.0,"x_offset":15,"y_offset":10,"print_obj":true,"lock_aspect_ratio":false,"locked":false},"legend":{"position":"left","show_legend_key":false},"title":{"name":"Fruit 2D Column Chart"},"plotarea":{"show_bubble_size":true,"show_cat_name":false,"show_leader_lines":false,"show_percent":true,"show_series_name":true,"show_val":true},"show_blanks_as":"zero"}`)
xlsx.AddChart("Sheet1", "X1", `{"type":"colStacked","series":[{"name":"Sheet1!$A$30","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$30:$D$30"},{"name":"Sheet1!$A$31","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$31:$D$31"},{"name":"Sheet1!$A$32","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$32:$D$32"}],"format":{"x_scale":1.0,"y_scale":1.0,"x_offset":15,"y_offset":10,"print_obj":true,"lock_aspect_ratio":false,"locked":false},"legend":{"position":"left","show_legend_key":false},"title":{"name":"Fruit 2D Stacked Column Chart"},"plotarea":{"show_bubble_size":true,"show_cat_name":false,"show_leader_lines":false,"show_percent":true,"show_series_name":true,"show_val":true},"show_blanks_as":"zero"}`)
xlsx.AddChart("Sheet1", "P16", `{"type":"colPercentStacked","series":[{"name":"Sheet1!$A$30","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$30:$D$30"},{"name":"Sheet1!$A$31","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$31:$D$31"},{"name":"Sheet1!$A$32","categories":"Sheet1!$B$29:$D$29","values":"Sheet1!$B$32:$D$32"}],"format":{"x_scale":1.0,"y_scale":1.0,"x_offset":15,"y_offset":10,"print_obj":true,"lock_aspect_ratio":false,"locked":false},"legend":{"position":"left","show_legend_key":false},"title":{"name":"Fruit 100% Stacked Column Chart"},"plotarea":{"show_bubble_size":true,"show_cat_name":false,"show_leader_lines":false,"show_percent":true,"show_series_name":true,"show_val":true},"show_blanks_as":"zero"}`)
Expand Down Expand Up @@ -937,6 +954,7 @@ func TestSetPane(t *testing.T) {
xlsx.SetPanes("Panes 3", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"top_left_cell":"N57","active_pane":"bottomLeft","panes":[{"sqref":"I36","active_cell":"I36"},{"sqref":"G33","active_cell":"G33","pane":"topRight"},{"sqref":"J60","active_cell":"J60","pane":"bottomLeft"},{"sqref":"O60","active_cell":"O60","pane":"bottomRight"}]}`)
xlsx.NewSheet("Panes 4")
xlsx.SetPanes("Panes 4", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"top_left_cell":"A34","active_pane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`)
xlsx.SetPanes("Panes 4", "")
err := xlsx.SaveAs("./test/Book_set_panes.xlsx")
if err != nil {
t.Error(err)
Expand Down Expand Up @@ -1010,6 +1028,8 @@ func TestConditionalFormat(t *testing.T) {
xlsx.SetConditionalFormat("Sheet1", "K1:K10", `[{"type":"data_bar", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`)
// Use a formula to determine which cells to format.
xlsx.SetConditionalFormat("Sheet1", "L1:L10", fmt.Sprintf(`[{"type":"formula", "criteria":"L2<3", "format":%d}]`, format1))
// Test set invalid format set in conditional format
xlsx.SetConditionalFormat("Sheet1", "L1:L10", "")
err = xlsx.SaveAs("./test/Book_conditional_format.xlsx")
if err != nil {
t.Log(err)
Expand Down
2 changes: 1 addition & 1 deletion lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func readFile(file *zip.File) []byte {
log.Fatal(err)
}
buff := bytes.NewBuffer(nil)
io.Copy(buff, rc)
_, _ = io.Copy(buff, rc)
rc.Close()
return buff.Bytes()
}
Expand Down
29 changes: 16 additions & 13 deletions picture.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (

// parseFormatPictureSet provides function to parse the format settings of the
// picture with default value.
func parseFormatPictureSet(formatSet string) *formatPicture {
func parseFormatPictureSet(formatSet string) (*formatPicture, error) {
format := formatPicture{
FPrintsWithSheet: true,
FLocksWithSheet: false,
Expand All @@ -26,8 +26,8 @@ func parseFormatPictureSet(formatSet string) *formatPicture {
XScale: 1.0,
YScale: 1.0,
}
json.Unmarshal([]byte(formatSet), &format)
return &format
err := json.Unmarshal([]byte(formatSet), &format)
return &format, err
}

// AddPicture provides the method to add picture in a sheet by given picture
Expand Down Expand Up @@ -89,9 +89,12 @@ func (f *File) AddPicture(sheet, cell, picture, format string) error {
return errors.New("Unsupported image extension")
}
readFile, _ := os.Open(picture)
image, _, err := image.DecodeConfig(readFile)
image, _, _ := image.DecodeConfig(readFile)
_, file := filepath.Split(picture)
formatSet := parseFormatPictureSet(format)
formatSet, err := parseFormatPictureSet(format)
if err != nil {
return err
}
// Read sheet data.
xlsx := f.workSheetReader(sheet)
// Add first picture for given sheet, create xl/drawings/ and xl/drawings/_rels/ folder.
Expand Down Expand Up @@ -130,7 +133,7 @@ func (f *File) addSheetRelationships(sheet, relType, target, targetMode string)
_, ok = f.XLSX[rels]
if ok {
ID.Reset()
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
rID = len(sheetRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
Expand All @@ -156,7 +159,7 @@ func (f *File) deleteSheetRelationships(sheet, rID string) {
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
for k, v := range sheetRels.Relationships {
if v.ID == rID {
sheetRels.Relationships = append(sheetRels.Relationships[:k], sheetRels.Relationships[k+1:]...)
Expand Down Expand Up @@ -273,7 +276,7 @@ func (f *File) addDrawingRelationships(index int, relType, target, targetMode st
_, ok := f.XLSX[rels]
if ok {
ID.Reset()
xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
rID = len(drawingRels.Relationships) + 1
ID.WriteString("rId")
ID.WriteString(strconv.Itoa(rID))
Expand Down Expand Up @@ -394,7 +397,7 @@ func (f *File) getSheetRelationshipsTargetByID(sheet, rID string) string {
}
var rels = "xl/worksheets/_rels/" + strings.TrimPrefix(name, "xl/worksheets/") + ".rels"
var sheetRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &sheetRels)
for _, v := range sheetRels.Relationships {
if v.ID == rID {
return v.Target
Expand Down Expand Up @@ -431,10 +434,10 @@ func (f *File) GetPicture(sheet, cell string) (string, []byte) {

_, ok := f.XLSX[drawingXML]
if !ok {
return "", []byte{}
return "", nil
}
decodeWsDr := decodeWsDr{}
xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)
_ = xml.Unmarshal([]byte(f.readXML(drawingXML)), &decodeWsDr)

cell = strings.ToUpper(cell)
fromCol := string(strings.Map(letterOnlyMapF, cell))
Expand All @@ -446,7 +449,7 @@ func (f *File) GetPicture(sheet, cell string) (string, []byte) {

for _, anchor := range decodeWsDr.TwoCellAnchor {
decodeTwoCellAnchor := decodeTwoCellAnchor{}
xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
_ = xml.Unmarshal([]byte("<decodeTwoCellAnchor>"+anchor.Content+"</decodeTwoCellAnchor>"), &decodeTwoCellAnchor)
if decodeTwoCellAnchor.From != nil && decodeTwoCellAnchor.Pic != nil {
if decodeTwoCellAnchor.From.Col == col && decodeTwoCellAnchor.From.Row == row {
xlsxWorkbookRelation := f.getDrawingRelationships(drawingRelationships, decodeTwoCellAnchor.Pic.BlipFill.Blip.Embed)
Expand All @@ -468,7 +471,7 @@ func (f *File) getDrawingRelationships(rels, rID string) *xlsxWorkbookRelation {
return nil
}
var drawingRels xlsxWorkbookRels
xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
_ = xml.Unmarshal([]byte(f.readXML(rels)), &drawingRels)
for _, v := range drawingRels.Relationships {
if v.ID == rID {
return &v
Expand Down
14 changes: 7 additions & 7 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (f *File) GetRows(sheet string) [][]string {
output, _ := xml.Marshal(f.Sheet[name])
f.saveFileList(name, replaceWorkSheetsRelationshipsNameSpaceBytes(output))
}
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
xml.NewDecoder(bytes.NewReader(f.readXML(name)))
d := f.sharedStringsReader()
var inElement string
var r xlsxRow
Expand All @@ -44,7 +44,7 @@ func (f *File) GetRows(sheet string) [][]string {
}
rows = append(rows, row)
}
decoder = xml.NewDecoder(bytes.NewReader(f.readXML(name)))
decoder := xml.NewDecoder(bytes.NewReader(f.readXML(name)))
for {
token, _ := decoder.Token()
if token == nil {
Expand All @@ -55,7 +55,7 @@ func (f *File) GetRows(sheet string) [][]string {
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
decoder.DecodeElement(&r, &startElement)
_ = decoder.DecodeElement(&r, &startElement)
cr := r.R - 1
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
Expand Down Expand Up @@ -110,9 +110,9 @@ func (rows *Rows) Columns() []string {
}
startElement := rows.token.(xml.StartElement)
r := xlsxRow{}
rows.decoder.DecodeElement(&r, &startElement)
_ = rows.decoder.DecodeElement(&r, &startElement)
d := rows.f.sharedStringsReader()
row := make([]string, len(r.C), len(r.C))
row := make([]string, len(r.C))
for _, colCell := range r.C {
c := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
val, _ := colCell.getValueFrom(rows.f, d)
Expand Down Expand Up @@ -173,7 +173,7 @@ func (f *File) getTotalRowsCols(name string) (int, int) {
inElement = startElement.Name.Local
if inElement == "row" {
r = xlsxRow{}
decoder.DecodeElement(&r, &startElement)
_ = decoder.DecodeElement(&r, &startElement)
tr = r.R
for _, colCell := range r.C {
col := TitleToNumber(strings.Map(letterOnlyMapF, colCell.R))
Expand Down Expand Up @@ -240,7 +240,7 @@ func (f *File) sharedStringsReader() *xlsxSST {
if len(ss) == 0 {
ss = f.readXML("xl/SharedStrings.xml")
}
xml.Unmarshal([]byte(ss), &sharedStrings)
_ = xml.Unmarshal([]byte(ss), &sharedStrings)
f.SharedStrings = &sharedStrings
}
return f.SharedStrings
Expand Down
Loading

0 comments on commit 9e463b4

Please sign in to comment.