0

I have an Excel file created inside a cStringIO variable.

I need to open it and read it. But to open an excel file with the xlrd function xlrd.open_workbook(excel_file_name), I need to call it by its file name. But in this case there is no file name because it is a cStrinIO variable that contains the representation of the Excel file.

How can I convert the cStringIO variable into a real excel file that I can open?

Thank you!

Xar
  • 7,572
  • 19
  • 56
  • 80

2 Answers2

2

Looks like xlrd.open_workbook() accepts file_contents argument as well, so maybe as follows?

xlrd.open_workbook(file_contents=cstringio_var.getvalue())
Tommi Komulainen
  • 2,830
  • 1
  • 19
  • 16
  • 1
    Indeed. This is the right way for the original question. I'd like to keep my answer as a general workaround though :) – Felix Yan Apr 16 '14 at 14:14
  • Thank you both Felix and Tommi! Both answers worked for me, but I ended up using Tommi's since it is the way the function is designed to be used. – Xar Apr 16 '14 at 16:11
1

You can use tempfile.NamedTemporaryFile.

Example (not tested):

with tempfile.NamedTemporaryFile() as f:
    f.write(your_cStringIO_variable.read())
    f.flush()
    something = xlrd.open_workbook(f.name)
Felix Yan
  • 14,841
  • 7
  • 48
  • 61