file.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. if len(f.Sheets) == 0 {
  101. sheet.Selected = true
  102. }
  103. f.Sheet[sheetName] = sheet
  104. f.Sheets = append(f.Sheets, sheet)
  105. return sheet
  106. }
  107. func (f *File) makeWorkbook() xlsxWorkbook {
  108. var workbook xlsxWorkbook
  109. workbook = xlsxWorkbook{}
  110. workbook.FileVersion = xlsxFileVersion{}
  111. workbook.FileVersion.AppName = "Go XLSX"
  112. workbook.WorkbookPr = xlsxWorkbookPr{
  113. BackupFile: false,
  114. ShowObjects: "all"}
  115. workbook.BookViews = xlsxBookViews{}
  116. workbook.BookViews.WorkBookView = make([]xlsxWorkBookView, 1)
  117. workbook.BookViews.WorkBookView[0] = xlsxWorkBookView{
  118. ActiveTab: 0,
  119. FirstSheet: 0,
  120. ShowHorizontalScroll: true,
  121. ShowSheetTabs: true,
  122. ShowVerticalScroll: true,
  123. TabRatio: 204,
  124. WindowHeight: 8192,
  125. WindowWidth: 16384,
  126. XWindow: "0",
  127. YWindow: "0"}
  128. workbook.Sheets = xlsxSheets{}
  129. workbook.Sheets.Sheet = make([]xlsxSheet, len(f.Sheets))
  130. workbook.CalcPr.IterateCount = 100
  131. workbook.CalcPr.RefMode = "A1"
  132. workbook.CalcPr.Iterate = false
  133. workbook.CalcPr.IterateDelta = 0.001
  134. return workbook
  135. }
  136. //For importing excel at SAS, WorkkBook.SheetViews.Sheet's node string(including two attribute xmlns:relationships, relationships:id)
  137. //`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id` should be replaced to `r:id`
  138. func replacingWorkbookSheetId(workbookMarshal string) string {
  139. return strings.Replace(workbookMarshal, `xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id`, `r:id`, -1)
  140. }
  141. // Construct a map of file name to XML content representing the file
  142. // in terms of the structure of an XLSX file.
  143. func (f *File) MarshallParts() (map[string]string, error) {
  144. var parts map[string]string
  145. var refTable *RefTable = NewSharedStringRefTable()
  146. refTable.isWrite = true
  147. var workbookRels WorkBookRels = make(WorkBookRels)
  148. var err error
  149. var workbook xlsxWorkbook
  150. var types xlsxTypes = MakeDefaultContentTypes()
  151. marshal := func(thing interface{}) (string, error) {
  152. body, err := xml.Marshal(thing)
  153. if err != nil {
  154. return "", err
  155. }
  156. return xml.Header + string(body), nil
  157. }
  158. parts = make(map[string]string)
  159. workbook = f.makeWorkbook()
  160. sheetIndex := 1
  161. if f.styles == nil {
  162. f.styles = newXlsxStyleSheet(f.theme)
  163. }
  164. f.styles.reset()
  165. for _, sheet := range f.Sheets {
  166. xSheet := sheet.makeXLSXSheet(refTable, f.styles)
  167. rId := fmt.Sprintf("rId%d", sheetIndex)
  168. sheetId := strconv.Itoa(sheetIndex)
  169. sheetPath := fmt.Sprintf("worksheets/sheet%d.xml", sheetIndex)
  170. partName := "xl/" + sheetPath
  171. types.Overrides = append(
  172. types.Overrides,
  173. xlsxOverride{
  174. PartName: "/" + partName,
  175. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"})
  176. workbookRels[rId] = sheetPath
  177. workbook.Sheets.Sheet[sheetIndex-1] = xlsxSheet{
  178. Name: sheet.Name,
  179. SheetId: sheetId,
  180. Id: rId,
  181. State: "visible"}
  182. parts[partName], err = marshal(xSheet)
  183. if err != nil {
  184. return parts, err
  185. }
  186. sheetIndex++
  187. }
  188. workbookMarshal, err := marshal(workbook)
  189. if err != nil {
  190. return parts, err
  191. }
  192. workbookMarshal = replacingWorkbookSheetId(workbookMarshal)
  193. parts["xl/workbook.xml"] = workbookMarshal
  194. if err != nil {
  195. return parts, err
  196. }
  197. // Make it work with Mac Numbers.
  198. // Dirty hack to fix issues #63 and #91; encoding/xml currently
  199. // "doesn't allow for additional namespaces to be defined in the root element of the document,"
  200. // as described by @tealeg in the comments for #63.
  201. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  202. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">`
  203. parts["xl/workbook.xml"] = strings.Replace(parts["xl/workbook.xml"], oldXmlns, newXmlns, 1)
  204. parts["_rels/.rels"] = TEMPLATE__RELS_DOT_RELS
  205. parts["docProps/app.xml"] = TEMPLATE_DOCPROPS_APP
  206. // TODO - do this properly, modification and revision information
  207. parts["docProps/core.xml"] = TEMPLATE_DOCPROPS_CORE
  208. parts["xl/theme/theme1.xml"] = TEMPLATE_XL_THEME_THEME
  209. xSST := refTable.makeXLSXSST()
  210. parts["xl/sharedStrings.xml"], err = marshal(xSST)
  211. if err != nil {
  212. return parts, err
  213. }
  214. xWRel := workbookRels.MakeXLSXWorkbookRels()
  215. parts["xl/_rels/workbook.xml.rels"], err = marshal(xWRel)
  216. if err != nil {
  217. return parts, err
  218. }
  219. parts["[Content_Types].xml"], err = marshal(types)
  220. if err != nil {
  221. return parts, err
  222. }
  223. parts["xl/styles.xml"], err = f.styles.Marshal()
  224. if err != nil {
  225. return parts, err
  226. }
  227. return parts, nil
  228. }
  229. // Return the raw data contained in the File as three
  230. // dimensional slice. The first index represents the sheet number,
  231. // the second the row number, and the third the cell number.
  232. //
  233. // For example:
  234. //
  235. // var mySlice [][][]string
  236. // var value string
  237. // mySlice = xlsx.FileToSlice("myXLSX.xlsx")
  238. // value = mySlice[0][0][0]
  239. //
  240. // Here, value would be set to the raw value of the cell A1 in the
  241. // first sheet in the XLSX file.
  242. func (file *File) ToSlice() (output [][][]string, err error) {
  243. output = [][][]string{}
  244. for _, sheet := range file.Sheets {
  245. s := [][]string{}
  246. for _, row := range sheet.Rows {
  247. if row == nil {
  248. continue
  249. }
  250. r := []string{}
  251. for _, cell := range row.Cells {
  252. r = append(r, cell.String())
  253. }
  254. s = append(s, r)
  255. }
  256. output = append(output, s)
  257. }
  258. return output, nil
  259. }