file.go 10 KB

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