file.go 9.0 KB

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