How do I download an xlsm file and read every shee

2019-08-18 11:05发布

问题:

Right now I am doing the following.

import xlrd

resp = requests.get(url, auth=auth).content
output = open(r'temp.xlsx', 'wb')
output.write(resp)
output.close()
xl = xlrd.open_workbook(r'temp.xlsx')
sh = 1
try:
    for sheet in xl.sheets():
    xls.append(sheet.name)
except:
    xls = ['']

It's extracting the sheets but I don't know how to read the file or if saving the file as an .xlsx is actually working for macros. All I know is that the code is not working right now and I need to be able to catch the data that is being generated in a macro. Please help! Thanks.

回答1:

I highly recommend using xlwings if you want to open, modify, and save .xlsm files without corrupting them. I have tried a ton of different methods (using other modules like openpyxl) and the macros always end up being corrupted.

import xlwings as xw
app = xw.App(visible=False) # IF YOU WANT EXCEL TO RUN IN BACKGROUND

xlwb = xw.Book('PATH\\TO\\FILE.xlsm')
xlws = {}
xlws['ws1'] = xlwb.sheets['Your Worksheet']

print(xlws['ws1'].range('B1').value)   # get value
xlws['ws1'].range('B1').value =  'New Value'   # change value

yourMacro = xlwb.macro('YourExcelMacro')
yourMacro()

xlwb.save()
xlwb.close()

Edit - I added an option to keep Excel invisible at users request