sheet.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "errors"
  6. "os"
  7. "path"
  8. "strconv"
  9. "strings"
  10. )
  11. // NewSheet provides function to create a new sheet by given index, when
  12. // creating a new XLSX file, the default sheet will be create, when you create a
  13. // new file, you need to ensure that the index is continuous.
  14. func (f *File) NewSheet(index int, name string) {
  15. // Update docProps/app.xml
  16. f.setAppXML()
  17. // Update [Content_Types].xml
  18. f.setContentTypes(index)
  19. // Create new sheet /xl/worksheets/sheet%d.xml
  20. f.setSheet(index)
  21. // Update xl/_rels/workbook.xml.rels
  22. rID := f.addXlsxWorkbookRels(index)
  23. // Update xl/workbook.xml
  24. f.setWorkbook(name, rID)
  25. f.SheetCount++
  26. }
  27. // contentTypesReader provides function to get the pointer to the
  28. // [Content_Types].xml structure after deserialization.
  29. func (f *File) contentTypesReader() *xlsxTypes {
  30. if f.ContentTypes == nil {
  31. var content xlsxTypes
  32. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  33. f.ContentTypes = &content
  34. }
  35. return f.ContentTypes
  36. }
  37. // contentTypesWriter provides function to save [Content_Types].xml after
  38. // serialize structure.
  39. func (f *File) contentTypesWriter() {
  40. if f.ContentTypes != nil {
  41. output, _ := xml.Marshal(f.ContentTypes)
  42. f.saveFileList("[Content_Types].xml", string(output))
  43. }
  44. }
  45. // workbookReader provides function to get the pointer to the xl/workbook.xml
  46. // structure after deserialization.
  47. func (f *File) workbookReader() *xlsxWorkbook {
  48. if f.WorkBook == nil {
  49. var content xlsxWorkbook
  50. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  51. f.WorkBook = &content
  52. }
  53. return f.WorkBook
  54. }
  55. // workbookWriter provides function to save xl/workbook.xml after serialize
  56. // structure.
  57. func (f *File) workbookWriter() {
  58. if f.WorkBook != nil {
  59. output, _ := xml.Marshal(f.WorkBook)
  60. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  61. }
  62. }
  63. // worksheetWriter provides function to save xl/worksheets/sheet%d.xml after
  64. // serialize structure.
  65. func (f *File) worksheetWriter() {
  66. for path, sheet := range f.Sheet {
  67. if sheet != nil {
  68. output, _ := xml.Marshal(sheet)
  69. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  70. }
  71. }
  72. }
  73. // Read and update property of contents type of XLSX.
  74. func (f *File) setContentTypes(index int) {
  75. content := f.contentTypesReader()
  76. content.Overrides = append(content.Overrides, xlsxOverride{
  77. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  78. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  79. })
  80. }
  81. // Update sheet property by given index.
  82. func (f *File) setSheet(index int) {
  83. var xlsx xlsxWorksheet
  84. xlsx.Dimension.Ref = "A1"
  85. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  86. WorkbookViewID: 0,
  87. })
  88. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  89. f.Sheet[path] = &xlsx
  90. }
  91. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  92. // allowed in sheet title.
  93. func (f *File) setWorkbook(name string, rid int) {
  94. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  95. name = r.Replace(name)
  96. if len(name) > 31 {
  97. name = name[0:31]
  98. }
  99. content := f.workbookReader()
  100. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  101. Name: name,
  102. SheetID: strconv.Itoa(rid),
  103. ID: "rId" + strconv.Itoa(rid),
  104. })
  105. }
  106. // workbookRelsReader provides function to read and unmarshal workbook
  107. // relationships of XLSX file.
  108. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  109. if f.WorkBookRels == nil {
  110. var content xlsxWorkbookRels
  111. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  112. f.WorkBookRels = &content
  113. }
  114. return f.WorkBookRels
  115. }
  116. // workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
  117. // serialize structure.
  118. func (f *File) workbookRelsWriter() {
  119. if f.WorkBookRels != nil {
  120. output, _ := xml.Marshal(f.WorkBookRels)
  121. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  122. }
  123. }
  124. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  125. func (f *File) addXlsxWorkbookRels(sheet int) int {
  126. content := f.workbookRelsReader()
  127. rID := 0
  128. for _, v := range content.Relationships {
  129. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  130. if t > rID {
  131. rID = t
  132. }
  133. }
  134. rID++
  135. ID := bytes.Buffer{}
  136. ID.WriteString("rId")
  137. ID.WriteString(strconv.Itoa(rID))
  138. target := bytes.Buffer{}
  139. target.WriteString("worksheets/sheet")
  140. target.WriteString(strconv.Itoa(sheet))
  141. target.WriteString(".xml")
  142. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  143. ID: ID.String(),
  144. Target: target.String(),
  145. Type: SourceRelationshipWorkSheet,
  146. })
  147. return rID
  148. }
  149. // setAppXML update docProps/app.xml file of XML.
  150. func (f *File) setAppXML() {
  151. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  152. }
  153. // Some tools that read XLSX files have very strict requirements about the
  154. // structure of the input XML. In particular both Numbers on the Mac and SAS
  155. // dislike inline XML namespace declarations, or namespace prefixes that don't
  156. // match the ones that Excel itself uses. This is a problem because the Go XML
  157. // library doesn't multiple namespace declarations in a single element of a
  158. // document. This function is a horrible hack to fix that after the XML
  159. // marshalling is completed.
  160. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  161. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  162. 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">`
  163. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  164. }
  165. // SetActiveSheet provides function to set default active sheet of XLSX by given
  166. // index.
  167. func (f *File) SetActiveSheet(index int) {
  168. if index < 1 {
  169. index = 1
  170. }
  171. index--
  172. content := f.workbookReader()
  173. if len(content.BookViews.WorkBookView) > 0 {
  174. content.BookViews.WorkBookView[0].ActiveTab = index
  175. } else {
  176. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  177. ActiveTab: index,
  178. })
  179. }
  180. sheets := len(content.Sheets.Sheet)
  181. index++
  182. for i := 0; i < sheets; i++ {
  183. sheetIndex := i + 1
  184. xlsx := f.workSheetReader("sheet" + strconv.Itoa(sheetIndex))
  185. if index == sheetIndex {
  186. if len(xlsx.SheetViews.SheetView) > 0 {
  187. xlsx.SheetViews.SheetView[0].TabSelected = true
  188. } else {
  189. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  190. TabSelected: true,
  191. })
  192. }
  193. } else {
  194. if len(xlsx.SheetViews.SheetView) > 0 {
  195. xlsx.SheetViews.SheetView[0].TabSelected = false
  196. }
  197. }
  198. }
  199. return
  200. }
  201. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  202. // found the active sheet will be return integer 0.
  203. func (f *File) GetActiveSheetIndex() int {
  204. buffer := bytes.Buffer{}
  205. content := f.workbookReader()
  206. for _, v := range content.Sheets.Sheet {
  207. xlsx := xlsxWorksheet{}
  208. buffer.WriteString("xl/worksheets/sheet")
  209. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  210. buffer.WriteString(".xml")
  211. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  212. for _, sheetView := range xlsx.SheetViews.SheetView {
  213. if sheetView.TabSelected {
  214. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  215. return ID
  216. }
  217. }
  218. buffer.Reset()
  219. }
  220. return 0
  221. }
  222. // SetSheetName provides function to set the sheet name be given old and new
  223. // sheet name. Maximum 31 characters are allowed in sheet title and this
  224. // function only changes the name of the sheet and will not update the sheet
  225. // name in the formula or reference associated with the cell. So there may be
  226. // problem formula error or reference missing.
  227. func (f *File) SetSheetName(oldName, newName string) {
  228. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  229. newName = r.Replace(newName)
  230. if len(newName) > 31 {
  231. newName = newName[0:31]
  232. }
  233. content := f.workbookReader()
  234. for k, v := range content.Sheets.Sheet {
  235. if v.Name == oldName {
  236. content.Sheets.Sheet[k].Name = newName
  237. }
  238. }
  239. }
  240. // GetSheetName provides function to get sheet name of XLSX by given sheet
  241. // index. If given sheet index is invalid, will return an empty string.
  242. func (f *File) GetSheetName(index int) string {
  243. content := f.workbookReader()
  244. for _, v := range content.Sheets.Sheet {
  245. if v.ID == "rId"+strconv.Itoa(index) {
  246. return v.Name
  247. }
  248. }
  249. return ""
  250. }
  251. // GetSheetMap provides function to get sheet map of XLSX. For example:
  252. //
  253. // xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
  254. // if err != nil {
  255. // fmt.Println(err)
  256. // os.Exit(1)
  257. // }
  258. // for k, v := range xlsx.GetSheetMap()
  259. // fmt.Println(k, v)
  260. // }
  261. //
  262. func (f *File) GetSheetMap() map[int]string {
  263. content := f.workbookReader()
  264. sheetMap := map[int]string{}
  265. for _, v := range content.Sheets.Sheet {
  266. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  267. sheetMap[id] = v.Name
  268. }
  269. return sheetMap
  270. }
  271. // SetSheetBackground provides function to set background picture by given sheet
  272. // index.
  273. func (f *File) SetSheetBackground(sheet, picture string) error {
  274. var err error
  275. // Check picture exists first.
  276. if _, err = os.Stat(picture); os.IsNotExist(err) {
  277. return err
  278. }
  279. ext, ok := supportImageTypes[path.Ext(picture)]
  280. if !ok {
  281. return errors.New("Unsupported image extension")
  282. }
  283. pictureID := f.countMedia() + 1
  284. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  285. f.addSheetPicture(sheet, rID)
  286. f.addMedia(picture, ext)
  287. f.setContentTypePartImageExtensions()
  288. return err
  289. }
  290. // DeleteSheet provides function to detele worksheet in a workbook by given
  291. // sheet name. Use this method with caution, which will affect changes in
  292. // references such as formulas, charts, and so on. If there is any referenced
  293. // value of the deleted worksheet, it will cause a file error when you open it.
  294. // This function will be invalid when only the one worksheet is left.
  295. func (f *File) DeleteSheet(name string) {
  296. content := f.workbookReader()
  297. for k, v := range content.Sheets.Sheet {
  298. if v.Name != name || len(content.Sheets.Sheet) < 2 {
  299. continue
  300. }
  301. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  302. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  303. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  304. target := f.deteleSheetFromWorkbookRels(v.ID)
  305. f.deteleSheetFromContentTypes(target)
  306. _, ok := f.XLSX[sheet]
  307. if ok {
  308. delete(f.XLSX, sheet)
  309. }
  310. _, ok = f.XLSX[rels]
  311. if ok {
  312. delete(f.XLSX, rels)
  313. }
  314. _, ok = f.Sheet[sheet]
  315. if ok {
  316. delete(f.Sheet, sheet)
  317. }
  318. f.SheetCount--
  319. }
  320. }
  321. // deteleSheetFromWorkbookRels provides function to remove worksheet
  322. // relationships by given relationships ID in the file
  323. // xl/_rels/workbook.xml.rels.
  324. func (f *File) deteleSheetFromWorkbookRels(rID string) string {
  325. content := f.workbookRelsReader()
  326. for k, v := range content.Relationships {
  327. if v.ID != rID {
  328. continue
  329. }
  330. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  331. return v.Target
  332. }
  333. return ""
  334. }
  335. // deteleSheetFromContentTypes provides function to remove worksheet
  336. // relationships by given target name in the file [Content_Types].xml.
  337. func (f *File) deteleSheetFromContentTypes(target string) {
  338. content := f.contentTypesReader()
  339. for k, v := range content.Overrides {
  340. if v.PartName != "/xl/"+target {
  341. continue
  342. }
  343. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  344. }
  345. }