sheet.go 7.6 KB

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