lib.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "io"
  5. "os"
  6. "xml"
  7. )
  8. // XLSXReaderError is the standard error type for otherwise undefined
  9. // errors in the XSLX reading process.
  10. type XLSXReaderError struct {
  11. Error string
  12. }
  13. // String() returns a string value from an XLSXReaderError struct in
  14. // order that it might comply with the os.Error interface.
  15. func (e *XLSXReaderError) String() string {
  16. return e.Error
  17. }
  18. // Sheet is a high level structure intended to provide user access to
  19. // the contents of a particular sheet within an XLSX file.
  20. type Sheet struct {
  21. }
  22. // File is a high level structure providing a slice of Sheet structs
  23. // to the user.
  24. type File struct {
  25. Sheets []*Sheet
  26. }
  27. // readSheetsFromZipFile is an internal helper function that loops
  28. // over the Worksheets defined in the XSLXWorkbook and loads them into
  29. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  30. func readSheetsFromZipFile(f *zip.File) ([]*Sheet, os.Error) {
  31. var workbook *XLSXWorkbook
  32. var error os.Error
  33. var rc io.ReadCloser
  34. workbook = new(XLSXWorkbook)
  35. rc, error = f.Open()
  36. if error != nil {
  37. return nil, error
  38. }
  39. error = xml.Unmarshal(rc, workbook)
  40. if error != nil {
  41. return nil, error
  42. }
  43. sheets := make([]*Sheet, len(workbook.Sheets.Sheet))
  44. for i, _ := range workbook.Sheets.Sheet {
  45. sheet := new(Sheet)
  46. sheets[i] = sheet
  47. }
  48. return sheets, nil
  49. }
  50. // OpenFile() take the name of an XLSX file and returns a populated
  51. // xlsx.File struct for it.
  52. func OpenFile(filename string) (x *File, e os.Error) {
  53. var f *zip.ReadCloser
  54. var error os.Error
  55. var xlsxFile *File
  56. var v *zip.File
  57. f, error = zip.OpenReader(filename)
  58. if error != nil {
  59. return nil, error
  60. }
  61. xlsxFile = new(File)
  62. for _, v = range f.File {
  63. if v.Name == "xl/workbook.xml" {
  64. sheets, error := readSheetsFromZipFile(v)
  65. if error != nil {
  66. return nil, error
  67. }
  68. if sheets == nil {
  69. error := new(XLSXReaderError)
  70. error.Error = "No sheets found in XLSX File"
  71. return nil, error
  72. }
  73. xlsxFile.Sheets = sheets
  74. }
  75. }
  76. f.Close()
  77. return xlsxFile, nil
  78. }