sheet.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. )
  9. // NewSheet provice function to greate a new sheet by given index, when
  10. // creating a new XLSX file, the default sheet will be create, when you
  11. // create a new file, you need to ensure that the index is continuous.
  12. func (f *File) NewSheet(index int, name string) {
  13. // Update docProps/app.xml
  14. f.setAppXML()
  15. // Update [Content_Types].xml
  16. f.setContentTypes(index)
  17. // Create new sheet /xl/worksheets/sheet%d.xml
  18. f.setSheet(index)
  19. // Update xl/_rels/workbook.xml.rels
  20. rid := f.addXlsxWorkbookRels(index)
  21. // Update xl/workbook.xml
  22. f.setWorkbook(name, rid)
  23. }
  24. // Read and update property of contents type of XLSX.
  25. func (f *File) setContentTypes(index int) {
  26. var content xlsxTypes
  27. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  28. content.Overrides = append(content.Overrides, xlsxOverride{
  29. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  30. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  31. })
  32. output, err := xml.Marshal(content)
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. f.saveFileList("[Content_Types].xml", string(output))
  37. }
  38. // Update sheet property by given index.
  39. func (f *File) setSheet(index int) {
  40. var xlsx xlsxWorksheet
  41. xlsx.Dimension.Ref = "A1"
  42. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  43. WorkbookViewID: 0,
  44. })
  45. output, err := xml.Marshal(xlsx)
  46. if err != nil {
  47. fmt.Println(err)
  48. }
  49. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  50. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  51. }
  52. // Update workbook property of XLSX. Maximum 31 characters are allowed in sheet title.
  53. func (f *File) setWorkbook(name string, rid int) {
  54. var content xlsxWorkbook
  55. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  56. name = r.Replace(name)
  57. if len(name) > 31 {
  58. name = name[0:31]
  59. }
  60. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  61. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  62. Name: name,
  63. SheetID: strconv.Itoa(rid),
  64. ID: "rId" + strconv.Itoa(rid),
  65. })
  66. output, err := xml.Marshal(content)
  67. if err != nil {
  68. fmt.Println(err)
  69. }
  70. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  71. }
  72. // Read and unmarshal workbook relationships of XLSX.
  73. func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
  74. var content xlsxWorkbookRels
  75. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  76. return content
  77. }
  78. // Update workbook relationships property of XLSX.
  79. func (f *File) addXlsxWorkbookRels(sheet int) int {
  80. content := f.readXlsxWorkbookRels()
  81. rID := len(content.Relationships) + 1
  82. ID := bytes.Buffer{}
  83. ID.WriteString("rId")
  84. ID.WriteString(strconv.Itoa(rID))
  85. target := bytes.Buffer{}
  86. target.WriteString("worksheets/sheet")
  87. target.WriteString(strconv.Itoa(sheet))
  88. target.WriteString(".xml")
  89. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  90. ID: ID.String(),
  91. Target: target.String(),
  92. Type: SourceRelationshipWorkSheet,
  93. })
  94. output, err := xml.Marshal(content)
  95. if err != nil {
  96. fmt.Println(err)
  97. }
  98. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  99. return rID
  100. }
  101. // Update docProps/app.xml file of XML.
  102. func (f *File) setAppXML() {
  103. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  104. }
  105. // Some tools that read XLSX files have very strict requirements about
  106. // the structure of the input XML. In particular both Numbers on the Mac
  107. // and SAS dislike inline XML namespace declarations, or namespace
  108. // prefixes that don't match the ones that Excel itself uses. This is a
  109. // problem because the Go XML library doesn't multiple namespace
  110. // declarations in a single element of a document. This function is a
  111. // horrible hack to fix that after the XML marshalling is completed.
  112. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  113. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  114. 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">`
  115. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  116. }
  117. // SetActiveSheet provide function to set default active sheet of XLSX by given index.
  118. func (f *File) SetActiveSheet(index int) {
  119. var content xlsxWorkbook
  120. if index < 1 {
  121. index = 1
  122. }
  123. index--
  124. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  125. if len(content.BookViews.WorkBookView) > 0 {
  126. content.BookViews.WorkBookView[0].ActiveTab = index
  127. } else {
  128. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  129. ActiveTab: index,
  130. })
  131. }
  132. sheets := len(content.Sheets.Sheet)
  133. output, err := xml.Marshal(content)
  134. if err != nil {
  135. fmt.Println(err)
  136. }
  137. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  138. index++
  139. buffer := bytes.Buffer{}
  140. for i := 0; i < sheets; i++ {
  141. xlsx := xlsxWorksheet{}
  142. sheetIndex := i + 1
  143. buffer.WriteString("xl/worksheets/sheet")
  144. buffer.WriteString(strconv.Itoa(sheetIndex))
  145. buffer.WriteString(".xml")
  146. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  147. if index == sheetIndex {
  148. if len(xlsx.SheetViews.SheetView) > 0 {
  149. xlsx.SheetViews.SheetView[0].TabSelected = true
  150. } else {
  151. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  152. TabSelected: true,
  153. })
  154. }
  155. } else {
  156. if len(xlsx.SheetViews.SheetView) > 0 {
  157. xlsx.SheetViews.SheetView[0].TabSelected = false
  158. }
  159. }
  160. sheet, err := xml.Marshal(xlsx)
  161. if err != nil {
  162. fmt.Println(err)
  163. }
  164. f.saveFileList(buffer.String(), replaceWorkSheetsRelationshipsNameSpace(string(sheet)))
  165. buffer.Reset()
  166. }
  167. return
  168. }
  169. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not found
  170. // the active sheet will be return integer 0.
  171. func (f *File) GetActiveSheetIndex() int {
  172. content := xlsxWorkbook{}
  173. buffer := bytes.Buffer{}
  174. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  175. for _, v := range content.Sheets.Sheet {
  176. xlsx := xlsxWorksheet{}
  177. buffer.WriteString("xl/worksheets/sheet")
  178. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  179. buffer.WriteString(".xml")
  180. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  181. for _, sheetView := range xlsx.SheetViews.SheetView {
  182. if sheetView.TabSelected {
  183. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  184. return id
  185. }
  186. }
  187. buffer.Reset()
  188. }
  189. return 0
  190. }
  191. // SetSheetName provides function to set the sheet name be given old and new sheet name.
  192. // Maximum 31 characters are allowed in sheet title and this function only changes the
  193. // name of the sheet and will not update the sheet name in the formula or reference
  194. // associated with the cell. So there may be problem formula error or reference missing.
  195. func (f *File) SetSheetName(oldName, newName string) {
  196. var content = xlsxWorkbook{}
  197. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  198. newName = r.Replace(newName)
  199. if len(newName) > 31 {
  200. newName = newName[0:31]
  201. }
  202. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  203. for k, v := range content.Sheets.Sheet {
  204. if v.Name == oldName {
  205. content.Sheets.Sheet[k].Name = newName
  206. }
  207. }
  208. output, _ := xml.Marshal(content)
  209. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  210. }
  211. // GetSheetName provides function to get sheet name of XLSX by given sheet index.
  212. // If given sheet index is invalid, will return an empty string.
  213. func (f *File) GetSheetName(index int) string {
  214. var content = xlsxWorkbook{}
  215. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  216. for _, v := range content.Sheets.Sheet {
  217. if v.ID == "rId"+strconv.Itoa(index) {
  218. return v.Name
  219. }
  220. }
  221. return ""
  222. }
  223. // GetSheetMap provides function to get sheet map of XLSX. For example:
  224. //
  225. // xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
  226. // if err != nil {
  227. // fmt.Println(err)
  228. // os.Exit(1)
  229. // }
  230. // for k, v := range xlsx.GetSheetMap()
  231. // fmt.Println(k, v)
  232. // }
  233. //
  234. func (f *File) GetSheetMap() map[int]string {
  235. content := xlsxWorkbook{}
  236. sheetMap := map[int]string{}
  237. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  238. for _, v := range content.Sheets.Sheet {
  239. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  240. sheetMap[id] = v.Name
  241. }
  242. return sheetMap
  243. }