file.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. // Iterate over the runes
  147. for _, r := range sheetName {
  148. // Excel forbids : \ / ? * [ ]
  149. if r == ':' || r == '\\' || r == '/' || r == '?' || r == '*' || r == '[' || r == ']' {
  150. return nil, fmt.Errorf("sheet name must not contain any restricted characters : \\ / ? * [ ] but contains '%s'", string(r))
  151. }
  152. }
  153. sheet := &Sheet{
  154. Name: sheetName,
  155. File: f,
  156. Selected: len(f.Sheets) == 0,
  157. }
  158. f.Sheet[sheetName] = sheet
  159. f.Sheets = append(f.Sheets, sheet)
  160. return sheet, nil
  161. }
  162. // Appends an existing Sheet, with the provided name, to a File
  163. func (f *File) AppendSheet(sheet Sheet, sheetName string) (*Sheet, error) {
  164. if _, exists := f.Sheet[sheetName]; exists {
  165. return nil, fmt.Errorf("duplicate sheet name '%s'.", sheetName)
  166. }
  167. sheet.Name = sheetName
  168. sheet.File = f
  169. sheet.Selected = len(f.Sheets) == 0
  170. f.Sheet[sheetName] = &sheet
  171. f.Sheets = append(f.Sheets, &sheet)
  172. return &sheet, nil
  173. }
  174. func (f *File) makeWorkbook() xlsxWorkbook {
  175. return xlsxWorkbook{
  176. FileVersion: xlsxFileVersion{AppName: "Go XLSX"},
  177. WorkbookPr: xlsxWorkbookPr{ShowObjects: "all"},
  178. BookViews: xlsxBookViews{
  179. WorkBookView: []xlsxWorkBookView{
  180. {
  181. ShowHorizontalScroll: true,
  182. ShowSheetTabs: true,
  183. ShowVerticalScroll: true,
  184. TabRatio: 204,
  185. WindowHeight: 8192,
  186. WindowWidth: 16384,
  187. XWindow: "0",
  188. YWindow: "0",
  189. },
  190. },
  191. },
  192. Sheets: xlsxSheets{Sheet: make([]xlsxSheet, len(f.Sheets))},
  193. CalcPr: xlsxCalcPr{
  194. IterateCount: 100,
  195. RefMode: "A1",
  196. Iterate: false,
  197. IterateDelta: 0.001,
  198. },
  199. }
  200. }
  201. // Some tools that read XLSX files have very strict requirements about
  202. // the structure of the input XML. In particular both Numbers on the Mac
  203. // and SAS dislike inline XML namespace declarations, or namespace
  204. // prefixes that don't match the ones that Excel itself uses. This is a
  205. // problem because the Go XML library doesn't multiple namespace
  206. // declarations in a single element of a document. This function is a
  207. // horrible hack to fix that after the XML marshalling is completed.
  208. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  209. newWorkbook := strings.Replace(workbookMarshal, `xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id`, `r:id`, -1)
  210. // Dirty hack to fix issues #63 and #91; encoding/xml currently
  211. // "doesn't allow for additional namespaces to be defined in the
  212. // root element of the document," as described by @tealeg in the
  213. // comments for #63.
  214. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  215. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">`
  216. return strings.Replace(newWorkbook, oldXmlns, newXmlns, 1)
  217. }
  218. // Construct a map of file name to XML content representing the file
  219. // in terms of the structure of an XLSX file.
  220. func (f *File) MarshallParts() (map[string]string, error) {
  221. var parts map[string]string
  222. var refTable *RefTable = NewSharedStringRefTable()
  223. refTable.isWrite = true
  224. var workbookRels WorkBookRels = make(WorkBookRels)
  225. var err error
  226. var workbook xlsxWorkbook
  227. var types xlsxTypes = MakeDefaultContentTypes()
  228. marshal := func(thing interface{}) (string, error) {
  229. body, err := xml.Marshal(thing)
  230. if err != nil {
  231. return "", err
  232. }
  233. return xml.Header + string(body), nil
  234. }
  235. parts = make(map[string]string)
  236. workbook = f.makeWorkbook()
  237. sheetIndex := 1
  238. if f.styles == nil {
  239. f.styles = newXlsxStyleSheet(f.theme)
  240. }
  241. f.styles.reset()
  242. if len(f.Sheets) == 0 {
  243. err := errors.New("Workbook must contains atleast one worksheet")
  244. return nil, err
  245. }
  246. for _, sheet := range f.Sheets {
  247. xSheet := sheet.makeXLSXSheet(refTable, f.styles)
  248. rId := fmt.Sprintf("rId%d", sheetIndex)
  249. sheetId := strconv.Itoa(sheetIndex)
  250. sheetPath := fmt.Sprintf("worksheets/sheet%d.xml", sheetIndex)
  251. partName := "xl/" + sheetPath
  252. types.Overrides = append(
  253. types.Overrides,
  254. xlsxOverride{
  255. PartName: "/" + partName,
  256. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"})
  257. workbookRels[rId] = sheetPath
  258. workbook.Sheets.Sheet[sheetIndex-1] = xlsxSheet{
  259. Name: sheet.Name,
  260. SheetId: sheetId,
  261. Id: rId,
  262. State: "visible"}
  263. parts[partName], err = marshal(xSheet)
  264. if err != nil {
  265. return parts, err
  266. }
  267. sheetIndex++
  268. }
  269. workbookMarshal, err := marshal(workbook)
  270. if err != nil {
  271. return parts, err
  272. }
  273. workbookMarshal = replaceRelationshipsNameSpace(workbookMarshal)
  274. parts["xl/workbook.xml"] = workbookMarshal
  275. if err != nil {
  276. return parts, err
  277. }
  278. parts["_rels/.rels"] = TEMPLATE__RELS_DOT_RELS
  279. parts["docProps/app.xml"] = TEMPLATE_DOCPROPS_APP
  280. // TODO - do this properly, modification and revision information
  281. parts["docProps/core.xml"] = TEMPLATE_DOCPROPS_CORE
  282. parts["xl/theme/theme1.xml"] = TEMPLATE_XL_THEME_THEME
  283. xSST := refTable.makeXLSXSST()
  284. parts["xl/sharedStrings.xml"], err = marshal(xSST)
  285. if err != nil {
  286. return parts, err
  287. }
  288. xWRel := workbookRels.MakeXLSXWorkbookRels()
  289. parts["xl/_rels/workbook.xml.rels"], err = marshal(xWRel)
  290. if err != nil {
  291. return parts, err
  292. }
  293. parts["[Content_Types].xml"], err = marshal(types)
  294. if err != nil {
  295. return parts, err
  296. }
  297. parts["xl/styles.xml"], err = f.styles.Marshal()
  298. if err != nil {
  299. return parts, err
  300. }
  301. return parts, nil
  302. }
  303. // Return the raw data contained in the File as three
  304. // dimensional slice. The first index represents the sheet number,
  305. // the second the row number, and the third the cell number.
  306. //
  307. // For example:
  308. //
  309. // var mySlice [][][]string
  310. // var value string
  311. // mySlice = xlsx.FileToSlice("myXLSX.xlsx")
  312. // value = mySlice[0][0][0]
  313. //
  314. // Here, value would be set to the raw value of the cell A1 in the
  315. // first sheet in the XLSX file.
  316. func (f *File) ToSlice() (output [][][]string, err error) {
  317. output = [][][]string{}
  318. for _, sheet := range f.Sheets {
  319. s := [][]string{}
  320. for _, row := range sheet.Rows {
  321. if row == nil {
  322. continue
  323. }
  324. r := []string{}
  325. for _, cell := range row.Cells {
  326. str, err := cell.FormattedValue()
  327. if err != nil {
  328. // Recover from strconv.NumError if the value is an empty string,
  329. // and insert an empty string in the output.
  330. if numErr, ok := err.(*strconv.NumError); ok && numErr.Num == "" {
  331. str = ""
  332. } else {
  333. return output, err
  334. }
  335. }
  336. r = append(r, str)
  337. }
  338. s = append(s, r)
  339. }
  340. output = append(output, s)
  341. }
  342. return output, nil
  343. }
  344. // ToSliceUnmerged returns the raw data contained in the File as three
  345. // dimensional slice (s. method ToSlice).
  346. // A covered cell become the value of its origin cell.
  347. // Example: table where A1:A2 merged.
  348. // | 01.01.2011 | Bread | 20 |
  349. // | | Fish | 70 |
  350. // This sheet will be converted to the slice:
  351. // [ [01.01.2011 Bread 20]
  352. // [01.01.2011 Fish 70] ]
  353. func (f *File) ToSliceUnmerged() (output [][][]string, err error) {
  354. output, err = f.ToSlice()
  355. if err != nil {
  356. return nil, err
  357. }
  358. for s, sheet := range f.Sheets {
  359. for r, row := range sheet.Rows {
  360. for c, cell := range row.Cells {
  361. if cell.HMerge > 0 {
  362. for i := c + 1; i <= c+cell.HMerge; i++ {
  363. output[s][r][i] = output[s][r][c]
  364. }
  365. }
  366. if cell.VMerge > 0 {
  367. for i := r + 1; i <= r+cell.VMerge; i++ {
  368. output[s][i][c] = output[s][r][c]
  369. }
  370. }
  371. }
  372. }
  373. }
  374. return output, nil
  375. }