file.go 8.7 KB

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