file.go 11 KB

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