sheet.go 7.6 KB

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