microsoft / python-in-excel

Python in Microsoft Excel
MIT License
531 stars 36 forks source link

Read in a range as list? #40

Open fzumstein opened 1 year ago

fzumstein commented 1 year ago

I am aware of the possibility to override the excel.set_xl_array_conversion with something like excel.set_xl_array_conversion(convert_to_list). But is there a way to leave the default as DataFrame, and just occasionally get a list, or is the idea to convert the DataFrame back to a list to do this?

keyur32 commented 1 year ago

The xl() function signature supports **kwargs, so you can pass additional parameters which are then pass to the conversion function, i.e. xl("A1:B5", headers=True, to_list=True)

Then check that to_list parameter as part of our convert_to_list and implement your logic accordingly.

keyur32 commented 1 year ago

Tagging as documentation (for when we enable support for editing of the Initialize pane).

fzumstein commented 1 year ago

Actually, I think overriding the default converter is easier. This is what I came up with:

def myconverter(x, headers=False, convert=None, **kwargs):
    if convert is None or convert == pd.DataFrame:
        return excel.convert_to_dataframe(x, headers=headers, **kwargs)
    elif convert == np.array:
        return np.array(x)
    elif convert == list:
        return x

excel.set_xl_array_conversion(myconverter)

This keeps the default unchanged, but allows for these:

xl(..., convert=np.array)
xl(..., convert=list)

As long as the initialize pane isn't editable, this can be placed in A1 of the first sheet.