file.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "encoding/xml"
  5. "fmt"
  6. "io"
  7. "os"
  8. "strconv"
  9. "strings"
  10. )
  11. // File is a high level structure providing a slice of Sheet structs
  12. // to the user.
  13. type File struct {
  14. worksheets map[string]*zip.File
  15. referenceTable *RefTable
  16. Date1904 bool
  17. styles *xlsxStyleSheet
  18. Sheets []*Sheet
  19. Sheet map[string]*Sheet
  20. theme *theme
  21. }
  22. // Create a new File
  23. func NewFile() (file *File) {
  24. file = &File{}
  25. file.Sheet = make(map[string]*Sheet)
  26. file.Sheets = make([]*Sheet, 0)
  27. return
  28. }
  29. // OpenFile() take the name of an XLSX file and returns a populated
  30. // xlsx.File struct for it.
  31. func OpenFile(filename string) (file *File, err error) {
  32. var f *zip.ReadCloser
  33. f, err = zip.OpenReader(filename)
  34. if err != nil {
  35. return nil, err
  36. }
  37. file, err = ReadZip(f)
  38. return
  39. }
  40. // A convenient wrapper around File.ToSlice, FileToSlice will
  41. // return the raw data contained in an Excel XLSX file as three
  42. // dimensional slice. The first index represents the sheet number,
  43. // the second the row number, and the third the cell number.
  44. //
  45. // For example:
  46. //
  47. // var mySlice [][][]string
  48. // var value string
  49. // mySlice = xlsx.FileToSlice("myXLSX.xlsx")
  50. // value = mySlice[0][0][0]
  51. //
  52. // Here, value would be set to the raw value of the cell A1 in the
  53. // first sheet in the XLSX file.
  54. func FileToSlice(path string) ([][][]string, error) {
  55. f, err := OpenFile(path)
  56. if err != nil {
  57. return nil, err
  58. }
  59. return f.ToSlice()
  60. }
  61. // Save the File to an xlsx file at the provided path.
  62. func (f *File) Save(path string) (err error) {
  63. var target *os.File
  64. target, err = os.Create(path)
  65. if err != nil {
  66. return
  67. }
  68. err = f.Write(target)
  69. if err != nil {
  70. return
  71. }
  72. return target.Close()
  73. }
  74. // Write the File to io.Writer as xlsx
  75. func (f *File) Write(writer io.Writer) (err error) {
  76. var parts map[string]string
  77. var zipWriter *zip.Writer
  78. parts, err = f.MarshallParts()
  79. if err != nil {
  80. return
  81. }
  82. zipWriter = zip.NewWriter(writer)
  83. for partName, part := range parts {
  84. var writer io.Writer
  85. writer, err = zipWriter.Create(partName)
  86. if err != nil {
  87. return
  88. }
  89. _, err = writer.Write([]byte(part))
  90. if err != nil {
  91. return
  92. }
  93. }
  94. err = zipWriter.Close()
  95. return
  96. }
  97. // Add a new Sheet, with the provided name, to a File
  98. func (f *File) AddSheet(sheetName string) (sheet *Sheet) {
  99. sheet = &Sheet{Name: sheetName, File: f}
  100. f.Sheet[sheetName] = sheet
  101. f.Sheets = append(f.Sheets, sheet)
  102. return sheet
  103. }
  104. func (f *File) makeWorkbook() xlsxWorkbook {
  105. var workbook xlsxWorkbook
  106. workbook = xlsxWorkbook{}
  107. workbook.FileVersion = xlsxFileVersion{}
  108. workbook.FileVersion.AppName = "Go XLSX"
  109. workbook.WorkbookPr = xlsxWorkbookPr{
  110. BackupFile: false,
  111. ShowObjects: "all"}
  112. workbook.BookViews = xlsxBookViews{}
  113. workbook.BookViews.WorkBookView = make([]xlsxWorkBookView, 1)
  114. workbook.BookViews.WorkBookView[0] = xlsxWorkBookView{
  115. ActiveTab: 0,
  116. FirstSheet: 0,
  117. ShowHorizontalScroll: true,
  118. ShowSheetTabs: true,
  119. ShowVerticalScroll: true,
  120. TabRatio: 204,
  121. WindowHeight: 8192,
  122. WindowWidth: 16384,
  123. XWindow: "0",
  124. YWindow: "0"}
  125. workbook.Sheets = xlsxSheets{}
  126. workbook.Sheets.Sheet = make([]xlsxSheet, len(f.Sheets))
  127. workbook.CalcPr.IterateCount = 100
  128. workbook.CalcPr.RefMode = "A1"
  129. workbook.CalcPr.Iterate = false
  130. workbook.CalcPr.IterateDelta = 0.001
  131. return workbook
  132. }
  133. // Construct a map of file name to XML content representing the file
  134. // in terms of the structure of an XLSX file.
  135. func (f *File) MarshallParts() (map[string]string, error) {
  136. var parts map[string]string
  137. var refTable *RefTable = NewSharedStringRefTable()
  138. refTable.isWrite = true
  139. var workbookRels WorkBookRels = make(WorkBookRels)
  140. var err error
  141. var workbook xlsxWorkbook
  142. var types xlsxTypes = MakeDefaultContentTypes()
  143. marshal := func(thing interface{}) (string, error) {
  144. body, err := xml.Marshal(thing)
  145. if err != nil {
  146. return "", err
  147. }
  148. return xml.Header + string(body), nil
  149. }
  150. parts = make(map[string]string)
  151. workbook = f.makeWorkbook()
  152. sheetIndex := 1
  153. if f.styles == nil {
  154. f.styles = newXlsxStyleSheet(f.theme)
  155. }
  156. f.styles.reset()
  157. for i, sheet := range f.Sheets {
  158. xSheet := sheet.makeXLSXSheet(refTable, f.styles)
  159. if i == 0 {
  160. xSheet.SheetViews.SheetView[0].TabSelected = true
  161. }
  162. rId := fmt.Sprintf("rId%d", sheetIndex)
  163. sheetId := strconv.Itoa(sheetIndex)
  164. sheetPath := fmt.Sprintf("worksheets/sheet%d.xml", sheetIndex)
  165. partName := "xl/" + sheetPath
  166. types.Overrides = append(
  167. types.Overrides,
  168. xlsxOverride{
  169. PartName: "/" + partName,
  170. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"})
  171. workbookRels[rId] = sheetPath
  172. workbook.Sheets.Sheet[sheetIndex-1] = xlsxSheet{
  173. Name: sheet.Name,
  174. SheetId: sheetId,
  175. Id: rId,
  176. State: "visible"}
  177. parts[partName], err = marshal(xSheet)
  178. if err != nil {
  179. return parts, err
  180. }
  181. sheetIndex++
  182. }
  183. parts["xl/workbook.xml"], err = marshal(workbook)
  184. if err != nil {
  185. return parts, err
  186. }
  187. // Make it work with Mac Numbers.
  188. // Dirty hack to fix issues #63 and #91; encoding/xml currently
  189. // "doesn't allow for additional namespaces to be defined in the root element of the document,"
  190. // as described by @tealeg in the comments for #63.
  191. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  192. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">`
  193. parts["xl/workbook.xml"] = strings.Replace(parts["xl/workbook.xml"], oldXmlns, newXmlns, 1)
  194. parts["_rels/.rels"] = TEMPLATE__RELS_DOT_RELS
  195. parts["docProps/app.xml"] = TEMPLATE_DOCPROPS_APP
  196. // TODO - do this properly, modification and revision information
  197. parts["docProps/core.xml"] = TEMPLATE_DOCPROPS_CORE
  198. parts["xl/theme/theme1.xml"] = TEMPLATE_XL_THEME_THEME
  199. xSST := refTable.makeXLSXSST()
  200. if xSST.Count > 0 || xSST.UniqueCount > 0 {
  201. parts["xl/sharedStrings.xml"], err = marshal(xSST)
  202. if err != nil {
  203. return parts, err
  204. }
  205. }
  206. xWRel := workbookRels.MakeXLSXWorkbookRels()
  207. parts["xl/_rels/workbook.xml.rels"], err = marshal(xWRel)
  208. if err != nil {
  209. return parts, err
  210. }
  211. parts["[Content_Types].xml"], err = marshal(types)
  212. if err != nil {
  213. return parts, err
  214. }
  215. parts["xl/styles.xml"], err = f.styles.Marshal()
  216. if err != nil {
  217. return parts, err
  218. }
  219. return parts, nil
  220. }
  221. // Return the raw data contained in the File as three
  222. // dimensional slice. The first index represents the sheet number,
  223. // the second the row number, and the third the cell number.
  224. //
  225. // For example:
  226. //
  227. // var mySlice [][][]string
  228. // var value string
  229. // mySlice = xlsx.FileToSlice("myXLSX.xlsx")
  230. // value = mySlice[0][0][0]
  231. //
  232. // Here, value would be set to the raw value of the cell A1 in the
  233. // first sheet in the XLSX file.
  234. func (file *File) ToSlice() (output [][][]string, err error) {
  235. output = [][][]string{}
  236. for _, sheet := range file.Sheets {
  237. s := [][]string{}
  238. for _, row := range sheet.Rows {
  239. if row == nil {
  240. continue
  241. }
  242. r := []string{}
  243. for _, cell := range row.Cells {
  244. r = append(r, cell.String())
  245. }
  246. s = append(s, r)
  247. }
  248. output = append(output, s)
  249. }
  250. return output, nil
  251. }