Read Excel file from Perspective upload component

Hi, based on other thread on this forum, I tried to implement excel reading capabilities to my project. Below is a part of my code which works fine:

def get_workbook(file_path):
    # type: (str) -> Workbook
    """Get workbook from specified location."""
    file_stream = None

    try:
        file_stream = FileInputStream(file_path)
        workbook = WorkbookFactory.create(file_stream)
        return Workbook(workbook)

    finally:
        if file_stream is not None:
            file_stream.close()

In this case, I am reading a file from my PC. My project requires user to upload the file using the Perspective upload component which then provides the file as bytes.
How should I take those bytes and create a Workbook from it?

I tried reading the file as bytes in script console like this:

bytes = system.file.readFileAsBytes(path)
wb = WorkbookFactory.create(bytes)

Which does not work and I am not surprised.

Wrap the bytes in a java ByteArrayInputStream. That can be fed to .create() just like a file stream.

1 Like