file.go 12 KB

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