sheet.go 8.6 KB
Newer Older
xurime's avatar
xurime 已提交
1 2 3
package excelize

import (
4
	"bytes"
xurime's avatar
xurime 已提交
5 6 7 8 9 10
	"encoding/xml"
	"fmt"
	"strconv"
	"strings"
)

11 12 13
// NewSheet provice function to greate a new sheet by given index, when creating
// a new XLSX file, the default sheet will be create, when you create a new
// file, you need to ensure that the index is continuous.
14
func (f *File) NewSheet(index int, name string) {
xurime's avatar
xurime 已提交
15
	// Update docProps/app.xml
16
	f.setAppXML()
xurime's avatar
xurime 已提交
17
	// Update [Content_Types].xml
18
	f.setContentTypes(index)
xurime's avatar
xurime 已提交
19
	// Create new sheet /xl/worksheets/sheet%d.xml
20
	f.setSheet(index)
xurime's avatar
xurime 已提交
21
	// Update xl/_rels/workbook.xml.rels
22
	rid := f.addXlsxWorkbookRels(index)
xurime's avatar
xurime 已提交
23
	// Update xl/workbook.xml
24
	f.setWorkbook(name, rid)
xurime's avatar
xurime 已提交
25 26
}

xurime's avatar
xurime 已提交
27
// Read and update property of contents type of XLSX.
28
func (f *File) setContentTypes(index int) {
xurime's avatar
xurime 已提交
29
	var content xlsxTypes
30
	xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
xurime's avatar
xurime 已提交
31
	content.Overrides = append(content.Overrides, xlsxOverride{
32 33
		PartName:    "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
		ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
xurime's avatar
xurime 已提交
34
	})
35
	output, err := xml.Marshal(content)
xurime's avatar
xurime 已提交
36 37 38
	if err != nil {
		fmt.Println(err)
	}
39
	f.saveFileList("[Content_Types].xml", string(output))
xurime's avatar
xurime 已提交
40 41
}

xurime's avatar
xurime 已提交
42
// Update sheet property by given index.
43
func (f *File) setSheet(index int) {
xurime's avatar
xurime 已提交
44
	var xlsx xlsxWorksheet
45
	xlsx.Dimension.Ref = "A1"
xurime's avatar
xurime 已提交
46
	xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
xurime's avatar
xurime 已提交
47
		WorkbookViewID: 0,
xurime's avatar
xurime 已提交
48
	})
49
	output, err := xml.Marshal(xlsx)
xurime's avatar
xurime 已提交
50 51 52
	if err != nil {
		fmt.Println(err)
	}
53
	path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
54
	f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
xurime's avatar
xurime 已提交
55 56
}

57 58
// setWorkbook update workbook property of XLSX. Maximum 31 characters are
// allowed in sheet title.
59
func (f *File) setWorkbook(name string, rid int) {
xurime's avatar
xurime 已提交
60
	var content xlsxWorkbook
61 62
	r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
	name = r.Replace(name)
63 64 65
	if len(name) > 31 {
		name = name[0:31]
	}
66
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
xurime's avatar
xurime 已提交
67 68
	content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
		Name:    name,
69
		SheetID: strconv.Itoa(rid),
70
		ID:      "rId" + strconv.Itoa(rid),
xurime's avatar
xurime 已提交
71
	})
72
	output, err := xml.Marshal(content)
xurime's avatar
xurime 已提交
73 74 75
	if err != nil {
		fmt.Println(err)
	}
76
	f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
xurime's avatar
xurime 已提交
77 78
}

79
// readXlsxWorkbookRels read and unmarshal workbook relationships of XLSX file.
80
func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
xurime's avatar
xurime 已提交
81
	var content xlsxWorkbookRels
82
	xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
xurime's avatar
xurime 已提交
83 84 85
	return content
}

86
// addXlsxWorkbookRels update workbook relationships property of XLSX.
87
func (f *File) addXlsxWorkbookRels(sheet int) int {
88
	content := f.readXlsxWorkbookRels()
xurime's avatar
xurime 已提交
89
	rID := len(content.Relationships) + 1
90
	ID := bytes.Buffer{}
91
	ID.WriteString("rId")
92 93
	ID.WriteString(strconv.Itoa(rID))
	target := bytes.Buffer{}
94
	target.WriteString("worksheets/sheet")
95
	target.WriteString(strconv.Itoa(sheet))
96
	target.WriteString(".xml")
xurime's avatar
xurime 已提交
97
	content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
98 99
		ID:     ID.String(),
		Target: target.String(),
100
		Type:   SourceRelationshipWorkSheet,
xurime's avatar
xurime 已提交
101
	})
102
	output, err := xml.Marshal(content)
xurime's avatar
xurime 已提交
103 104 105
	if err != nil {
		fmt.Println(err)
	}
106
	f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
107
	return rID
xurime's avatar
xurime 已提交
108 109
}

110
// setAppXML update docProps/app.xml file of XML.
111
func (f *File) setAppXML() {
112
	f.saveFileList("docProps/app.xml", templateDocpropsApp)
xurime's avatar
xurime 已提交
113 114
}

115 116 117 118 119 120 121
// Some tools that read XLSX files have very strict requirements about the
// structure of the input XML. In particular both Numbers on the Mac and SAS
// dislike inline XML namespace declarations, or namespace prefixes that don't
// match the ones that Excel itself uses. This is a problem because the Go XML
// library doesn't multiple namespace declarations in a single element of a
// document. This function is a horrible hack to fix that after the XML
// marshalling is completed.
xurime's avatar
xurime 已提交
122 123
func replaceRelationshipsNameSpace(workbookMarshal string) string {
	oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
124
	newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`
xurime's avatar
xurime 已提交
125 126 127
	return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
}

128
// SetActiveSheet provides function to set default active sheet of XLSX by given
129
// index.
130
func (f *File) SetActiveSheet(index int) {
xurime's avatar
xurime 已提交
131 132 133 134
	var content xlsxWorkbook
	if index < 1 {
		index = 1
	}
xurime's avatar
xurime 已提交
135
	index--
136
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
xurime's avatar
xurime 已提交
137 138 139 140 141 142 143 144
	if len(content.BookViews.WorkBookView) > 0 {
		content.BookViews.WorkBookView[0].ActiveTab = index
	} else {
		content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
			ActiveTab: index,
		})
	}
	sheets := len(content.Sheets.Sheet)
145
	output, err := xml.Marshal(content)
xurime's avatar
xurime 已提交
146 147 148
	if err != nil {
		fmt.Println(err)
	}
149
	f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
xurime's avatar
xurime 已提交
150
	index++
151
	buffer := bytes.Buffer{}
xurime's avatar
xurime 已提交
152 153 154
	for i := 0; i < sheets; i++ {
		xlsx := xlsxWorksheet{}
		sheetIndex := i + 1
155
		buffer.WriteString("xl/worksheets/sheet")
156
		buffer.WriteString(strconv.Itoa(sheetIndex))
157
		buffer.WriteString(".xml")
158
		xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
xurime's avatar
xurime 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171
		if index == sheetIndex {
			if len(xlsx.SheetViews.SheetView) > 0 {
				xlsx.SheetViews.SheetView[0].TabSelected = true
			} else {
				xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
					TabSelected: true,
				})
			}
		} else {
			if len(xlsx.SheetViews.SheetView) > 0 {
				xlsx.SheetViews.SheetView[0].TabSelected = false
			}
		}
172
		sheet, err := xml.Marshal(xlsx)
xurime's avatar
xurime 已提交
173 174 175
		if err != nil {
			fmt.Println(err)
		}
176
		f.saveFileList(buffer.String(), replaceWorkSheetsRelationshipsNameSpace(string(sheet)))
177
		buffer.Reset()
xurime's avatar
xurime 已提交
178
	}
179
	return
xurime's avatar
xurime 已提交
180 181
}

182 183
// GetActiveSheetIndex provides function to get active sheet of XLSX. If not
// found the active sheet will be return integer 0.
184 185 186
func (f *File) GetActiveSheetIndex() int {
	content := xlsxWorkbook{}
	buffer := bytes.Buffer{}
187
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
188 189
	for _, v := range content.Sheets.Sheet {
		xlsx := xlsxWorksheet{}
190 191 192
		buffer.WriteString("xl/worksheets/sheet")
		buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
		buffer.WriteString(".xml")
193 194 195
		xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
		for _, sheetView := range xlsx.SheetViews.SheetView {
			if sheetView.TabSelected {
196
				id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
197 198
				return id
			}
199
		}
200
		buffer.Reset()
201
	}
202
	return 0
203 204
}

205 206 207 208 209
// SetSheetName provides function to set the sheet name be given old and new
// sheet name. Maximum 31 characters are allowed in sheet title and this
// function only changes the name of the sheet and will not update the sheet
// name in the formula or reference associated with the cell. So there may be
// problem formula error or reference missing.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
func (f *File) SetSheetName(oldName, newName string) {
	var content = xlsxWorkbook{}
	r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
	newName = r.Replace(newName)
	if len(newName) > 31 {
		newName = newName[0:31]
	}
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
	for k, v := range content.Sheets.Sheet {
		if v.Name == oldName {
			content.Sheets.Sheet[k].Name = newName
		}
	}
	output, _ := xml.Marshal(content)
	f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
}

227 228
// GetSheetName provides function to get sheet name of XLSX by given sheet
// index. If given sheet index is invalid, will return an empty string.
229
func (f *File) GetSheetName(index int) string {
230 231
	var content = xlsxWorkbook{}
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
232
	for _, v := range content.Sheets.Sheet {
233
		if v.ID == "rId"+strconv.Itoa(index) {
234
			return v.Name
235 236
		}
	}
237
	return ""
238 239
}

240
// GetSheetMap provides function to get sheet map of XLSX. For example:
241 242 243 244 245 246 247 248 249 250 251 252 253
//
//    xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
//    if err != nil {
//        fmt.Println(err)
//        os.Exit(1)
//    }
//    for k, v := range xlsx.GetSheetMap()
//        fmt.Println(k, v)
//    }
//
func (f *File) GetSheetMap() map[int]string {
	content := xlsxWorkbook{}
	sheetMap := map[int]string{}
254
	xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
255
	for _, v := range content.Sheets.Sheet {
256
		id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
257 258 259
		sheetMap[id] = v.Name
	}
	return sheetMap
xurime's avatar
xurime 已提交
260
}