sheet.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package excelize
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. )
  8. // NewSheet provice function to greate a new sheet by given index, when
  9. // creating a new XLSX file, the default sheet will be create, when you
  10. // create a new file, you need to ensure that the index is continuous.
  11. func NewSheet(file []FileList, index int, name string) []FileList {
  12. // Update docProps/app.xml
  13. file = setAppXML(file)
  14. // Update [Content_Types].xml
  15. file = setContentTypes(file, index)
  16. // Create new sheet /xl/worksheets/sheet%d.xml
  17. file = setSheet(file, index)
  18. // Update xl/_rels/workbook.xml.rels
  19. file = addXlsxWorkbookRels(file, index)
  20. // Update xl/workbook.xml
  21. file = setWorkbook(file, index, name)
  22. return file
  23. }
  24. // Read and update property of contents type of XLSX
  25. func setContentTypes(file []FileList, index int) []FileList {
  26. var content xlsxTypes
  27. xml.Unmarshal([]byte(readXML(file, `[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.MarshalIndent(content, "", "")
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. return saveFileList(file, `[Content_Types].xml`, string(output))
  37. }
  38. // Update sheet property by given index
  39. func setSheet(file []FileList, index int) []FileList {
  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.MarshalIndent(xlsx, "", "")
  46. if err != nil {
  47. fmt.Println(err)
  48. }
  49. path := `xl/worksheets/sheet` + strconv.Itoa(index) + `.xml`
  50. return saveFileList(file, path, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  51. }
  52. // Update workbook property of XLSX
  53. func setWorkbook(file []FileList, index int, name string) []FileList {
  54. var content xlsxWorkbook
  55. xml.Unmarshal([]byte(readXML(file, `xl/workbook.xml`)), &content)
  56. rels := readXlsxWorkbookRels(file)
  57. rID := len(rels.Relationships)
  58. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  59. Name: name,
  60. SheetID: strconv.Itoa(index),
  61. ID: "rId" + strconv.Itoa(rID),
  62. })
  63. output, err := xml.MarshalIndent(content, "", "")
  64. if err != nil {
  65. fmt.Println(err)
  66. }
  67. return saveFileList(file, `xl/workbook.xml`, replaceRelationshipsNameSpace(string(output)))
  68. }
  69. // Read and unmarshal workbook relationships of XLSX
  70. func readXlsxWorkbookRels(file []FileList) xlsxWorkbookRels {
  71. var content xlsxWorkbookRels
  72. xml.Unmarshal([]byte(readXML(file, `xl/_rels/workbook.xml.rels`)), &content)
  73. return content
  74. }
  75. // Update workbook relationships property of XLSX
  76. func addXlsxWorkbookRels(file []FileList, sheet int) []FileList {
  77. content := readXlsxWorkbookRels(file)
  78. rID := len(content.Relationships) + 1
  79. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  80. ID: "rId" + strconv.Itoa(rID),
  81. Target: `worksheets/sheet` + strconv.Itoa(sheet) + `.xml`,
  82. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet",
  83. })
  84. output, err := xml.MarshalIndent(content, "", "")
  85. if err != nil {
  86. fmt.Println(err)
  87. }
  88. return saveFileList(file, `xl/_rels/workbook.xml.rels`, string(output))
  89. }
  90. // Update docProps/app.xml file of XML
  91. func setAppXML(file []FileList) []FileList {
  92. return saveFileList(file, `docProps/app.xml`, templateDocpropsApp)
  93. }
  94. // Some tools that read XLSX files have very strict requirements about
  95. // the structure of the input XML. In particular both Numbers on the Mac
  96. // and SAS dislike inline XML namespace declarations, or namespace
  97. // prefixes that don't match the ones that Excel itself uses. This is a
  98. // problem because the Go XML library doesn't multiple namespace
  99. // declarations in a single element of a document. This function is a
  100. // horrible hack to fix that after the XML marshalling is completed.
  101. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  102. // newWorkbook := strings.Replace(workbookMarshal, `xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id`, `r:id`, -1)
  103. // Dirty hack to fix issues #63 and #91; encoding/xml currently
  104. // "doesn't allow for additional namespaces to be defined in the
  105. // root element of the document," as described by @tealeg in the
  106. // comments for #63.
  107. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  108. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">`
  109. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  110. }
  111. // replace relationships ID in worksheets/sheet%d.xml
  112. func replaceRelationshipsID(workbookMarshal string) string {
  113. rids := strings.Replace(workbookMarshal, `<drawing rid="" />`, ``, -1)
  114. return strings.Replace(rids, `<drawing rid="`, `<drawing r:id="`, -1)
  115. }
  116. // SetActiveSheet provide function to set default active sheet of XLSX by given index
  117. func SetActiveSheet(file []FileList, index int) []FileList {
  118. var content xlsxWorkbook
  119. if index < 1 {
  120. index = 1
  121. }
  122. index--
  123. xml.Unmarshal([]byte(readXML(file, `xl/workbook.xml`)), &content)
  124. if len(content.BookViews.WorkBookView) > 0 {
  125. content.BookViews.WorkBookView[0].ActiveTab = index
  126. } else {
  127. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  128. ActiveTab: index,
  129. })
  130. }
  131. sheets := len(content.Sheets.Sheet)
  132. output, err := xml.MarshalIndent(content, "", "")
  133. if err != nil {
  134. fmt.Println(err)
  135. }
  136. file = saveFileList(file, `xl/workbook.xml`, workBookCompatibility(replaceRelationshipsNameSpace(string(output))))
  137. index++
  138. for i := 0; i < sheets; i++ {
  139. xlsx := xlsxWorksheet{}
  140. sheetIndex := i + 1
  141. path := `xl/worksheets/sheet` + strconv.Itoa(sheetIndex) + `.xml`
  142. xml.Unmarshal([]byte(readXML(file, path)), &xlsx)
  143. if index == sheetIndex {
  144. if len(xlsx.SheetViews.SheetView) > 0 {
  145. xlsx.SheetViews.SheetView[0].TabSelected = true
  146. } else {
  147. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  148. TabSelected: true,
  149. })
  150. }
  151. } else {
  152. if len(xlsx.SheetViews.SheetView) > 0 {
  153. xlsx.SheetViews.SheetView[0].TabSelected = false
  154. }
  155. }
  156. sheet, err := xml.MarshalIndent(xlsx, "", "")
  157. if err != nil {
  158. fmt.Println(err)
  159. }
  160. file = saveFileList(file, path, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(sheet))))
  161. }
  162. return file
  163. }
  164. // Replace xl/workbook.xml XML tags to self-closing for compatible Office Excel 2007
  165. func workBookCompatibility(workbookMarshal string) string {
  166. workbookMarshal = strings.Replace(workbookMarshal, `xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id="`, `r:id="`, -1)
  167. workbookMarshal = strings.Replace(workbookMarshal, `></sheet>`, ` />`, -1)
  168. workbookMarshal = strings.Replace(workbookMarshal, `></workbookView>`, ` />`, -1)
  169. workbookMarshal = strings.Replace(workbookMarshal, `></fileVersion>`, ` />`, -1)
  170. workbookMarshal = strings.Replace(workbookMarshal, `></workbookPr>`, ` />`, -1)
  171. workbookMarshal = strings.Replace(workbookMarshal, `></definedNames>`, ` />`, -1)
  172. workbookMarshal = strings.Replace(workbookMarshal, `></calcPr>`, ` />`, -1)
  173. workbookMarshal = strings.Replace(workbookMarshal, `></workbookProtection>`, ` />`, -1)
  174. workbookMarshal = strings.Replace(workbookMarshal, `></fileRecoveryPr>`, ` />`, -1)
  175. return workbookMarshal
  176. }