file.go 6.4 KB

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