file.go 6.3 KB

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