file.go 8.6 KB

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