file.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. if len(sheetName) >= 31 {
  117. return nil, fmt.Errorf("sheet name must be less than 31 characters long. It is currently '%d' characters long", len(sheetName))
  118. }
  119. sheet := &Sheet{
  120. Name: sheetName,
  121. File: f,
  122. Selected: len(f.Sheets) == 0,
  123. }
  124. f.Sheet[sheetName] = sheet
  125. f.Sheets = append(f.Sheets, sheet)
  126. return sheet, nil
  127. }
  128. // Appends an existing Sheet, with the provided name, to a File
  129. func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error) {
  130. if _, exists := f.Sheet[sheetName]; exists {
  131. return nil, fmt.Errorf("duplicate sheet name '%s'.", sheetName)
  132. }
  133. sheet.Name = sheetName
  134. sheet.File = f
  135. sheet.Selected = len(f.Sheets) == 0
  136. f.Sheet[sheetName] = &sheet
  137. f.Sheets = append(f.Sheets, &sheet)
  138. return &sheet, nil
  139. }
  140. func (f *File) makeWorkbook() xlsxWorkbook {
  141. return xlsxWorkbook{
  142. FileVersion: xlsxFileVersion{AppName: "Go XLSX"},
  143. WorkbookPr: xlsxWorkbookPr{ShowObjects: "all"},
  144. BookViews: xlsxBookViews{
  145. WorkBookView: []xlsxWorkBookView{
  146. {
  147. ShowHorizontalScroll: true,
  148. ShowSheetTabs: true,
  149. ShowVerticalScroll: true,
  150. TabRatio: 204,
  151. WindowHeight: 8192,
  152. WindowWidth: 16384,
  153. XWindow: "0",
  154. YWindow: "0",
  155. },
  156. },
  157. },
  158. Sheets: xlsxSheets{Sheet: make([]xlsxSheet, len(f.Sheets))},
  159. CalcPr: xlsxCalcPr{
  160. IterateCount: 100,
  161. RefMode: "A1",
  162. Iterate: false,
  163. IterateDelta: 0.001,
  164. },
  165. }
  166. }
  167. // Some tools that read XLSX files have very strict requirements about
  168. // the structure of the input XML. In particular both Numbers on the Mac
  169. // and SAS dislike inline XML namespace declarations, or namespace
  170. // prefixes that don't match the ones that Excel itself uses. This is a
  171. // problem because the Go XML library doesn't multiple namespace
  172. // declarations in a single element of a document. This function is a
  173. // horrible hack to fix that after the XML marshalling is completed.
  174. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  175. newWorkbook := strings.Replace(workbookMarshal, `xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id`, `r:id`, -1)
  176. // Dirty hack to fix issues #63 and #91; encoding/xml currently
  177. // "doesn't allow for additional namespaces to be defined in the
  178. // root element of the document," as described by @tealeg in the
  179. // comments for #63.
  180. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  181. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">`
  182. return strings.Replace(newWorkbook, oldXmlns, newXmlns, 1)
  183. }
  184. // Construct a map of file name to XML content representing the file
  185. // in terms of the structure of an XLSX file.
  186. func (f *File) MarshallParts() (map[string]string, error) {
  187. var parts map[string]string
  188. var refTable *RefTable = NewSharedStringRefTable()
  189. refTable.isWrite = true
  190. var workbookRels WorkBookRels = make(WorkBookRels)
  191. var err error
  192. var workbook xlsxWorkbook
  193. var types xlsxTypes = MakeDefaultContentTypes()
  194. marshal := func(thing interface{}) (string, error) {
  195. body, err := xml.Marshal(thing)
  196. if err != nil {
  197. return "", err
  198. }
  199. return xml.Header + string(body), nil
  200. }
  201. parts = make(map[string]string)
  202. workbook = f.makeWorkbook()
  203. sheetIndex := 1
  204. if f.styles == nil {
  205. f.styles = newXlsxStyleSheet(f.theme)
  206. }
  207. f.styles.reset()
  208. if len(f.Sheets) == 0 {
  209. err := errors.New("Workbook must contains atleast one worksheet")
  210. return nil, err
  211. }
  212. for _, sheet := range f.Sheets {
  213. xSheet := sheet.makeXLSXSheet(refTable, f.styles)
  214. rId := fmt.Sprintf("rId%d", sheetIndex)
  215. sheetId := strconv.Itoa(sheetIndex)
  216. sheetPath := fmt.Sprintf("worksheets/sheet%d.xml", sheetIndex)
  217. partName := "xl/" + sheetPath
  218. types.Overrides = append(
  219. types.Overrides,
  220. xlsxOverride{
  221. PartName: "/" + partName,
  222. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"})
  223. workbookRels[rId] = sheetPath
  224. workbook.Sheets.Sheet[sheetIndex-1] = xlsxSheet{
  225. Name: sheet.Name,
  226. SheetId: sheetId,
  227. Id: rId,
  228. State: "visible"}
  229. parts[partName], err = marshal(xSheet)
  230. if err != nil {
  231. return parts, err
  232. }
  233. sheetIndex++
  234. }
  235. workbookMarshal, err := marshal(workbook)
  236. if err != nil {
  237. return parts, err
  238. }
  239. workbookMarshal = replaceRelationshipsNameSpace(workbookMarshal)
  240. parts["xl/workbook.xml"] = workbookMarshal
  241. if err != nil {
  242. return parts, err
  243. }
  244. parts["_rels/.rels"] = TEMPLATE__RELS_DOT_RELS
  245. parts["docProps/app.xml"] = TEMPLATE_DOCPROPS_APP
  246. // TODO - do this properly, modification and revision information
  247. parts["docProps/core.xml"] = TEMPLATE_DOCPROPS_CORE
  248. parts["xl/theme/theme1.xml"] = TEMPLATE_XL_THEME_THEME
  249. xSST := refTable.makeXLSXSST()
  250. parts["xl/sharedStrings.xml"], err = marshal(xSST)
  251. if err != nil {
  252. return parts, err
  253. }
  254. xWRel := workbookRels.MakeXLSXWorkbookRels()
  255. parts["xl/_rels/workbook.xml.rels"], err = marshal(xWRel)
  256. if err != nil {
  257. return parts, err
  258. }
  259. parts["[Content_Types].xml"], err = marshal(types)
  260. if err != nil {
  261. return parts, err
  262. }
  263. parts["xl/styles.xml"], err = f.styles.Marshal()
  264. if err != nil {
  265. return parts, err
  266. }
  267. return parts, nil
  268. }
  269. // Return the raw data contained in the File as three
  270. // dimensional slice. The first index represents the sheet number,
  271. // the second the row number, and the third the cell number.
  272. //
  273. // For example:
  274. //
  275. // var mySlice [][][]string
  276. // var value string
  277. // mySlice = xlsx.FileToSlice("myXLSX.xlsx")
  278. // value = mySlice[0][0][0]
  279. //
  280. // Here, value would be set to the raw value of the cell A1 in the
  281. // first sheet in the XLSX file.
  282. func (file *File) ToSlice() (output [][][]string, err error) {
  283. output = [][][]string{}
  284. for _, sheet := range file.Sheets {
  285. s := [][]string{}
  286. for _, row := range sheet.Rows {
  287. if row == nil {
  288. continue
  289. }
  290. r := []string{}
  291. for _, cell := range row.Cells {
  292. str, err := cell.FormattedValue()
  293. if err != nil {
  294. // Recover from strconv.NumError if the value is an empty string,
  295. // and insert an empty string in the output.
  296. if numErr, ok := err.(*strconv.NumError); ok && numErr.Num == "" {
  297. str = ""
  298. } else {
  299. return output, err
  300. }
  301. }
  302. r = append(r, str)
  303. }
  304. s = append(s, r)
  305. }
  306. output = append(output, s)
  307. }
  308. return output, nil
  309. }