简体   繁体   English

Openpyxl load_workbook 索引错误仅与某个工作表有关

[英]Openpyxl load_workbook Index Error only with a certain worksheet

I am trying to read data from a single worksheet in an Excel workbook (Macro Enabled).我正在尝试从 Excel 工作簿(启用宏)中的单个工作表中读取数据。 The workbook comes with several other worksheets which I don't need anything from, one of which is giving me trouble.该工作簿附带了其他几个我不需要的工作表,其中一个给我带来了麻烦。 I can open the workbook in Excel with no issues, but using load_workbook with openpyxl results in an "IndexError: list index out of range".我可以毫无问题地在 Excel 中打开工作簿,但是将 load_workbook 与 openpyxl 一起使用会导致“IndexError:列表索引超出范围”。

I did lots of testing and found that the IndexError is triggered only when the troublesome worksheet is the last worksheet tab in the workbook.我做了很多测试,发现只有当麻烦的工作表是工作簿中的最后一个工作表选项卡时才会触发 IndexError。 If it is not the last worksheet in the workbook, I am able to use load_workbook with no issue.如果它不是工作簿中的最后一个工作表,我可以毫无问题地使用 load_workbook。 The troublesome worksheet itself contains an Excel print area.麻烦的工作表本身包含一个 Excel 打印区域。 If I remove that print area, I am able to use load_workbook with no issue.如果我删除该打印区域,我可以毫无问题地使用 load_workbook。

I need to programmatically read data from hundreds of workbooks with the same issue, so unfortunately I cannot just remove the bad worksheet in excel.我需要以编程方式从数百个具有相同问题的工作簿中读取数据,所以不幸的是我不能只删除 excel 中的坏工作表。

Is there anyone who is familiar with openpyxl and/or Excel at a lower level and knows what is happening here?有没有人在较低级别熟悉 openpyxl 和/或 Excel 并知道这里发生了什么?

Alternatively, does anyone know a way to do some pre-processing on a workbook without having to load it with load_workbook.或者,是否有人知道无需使用 load_workbook 加载工作簿即可对工作簿进行一些预处理的方法。 That way I can remove the bad worksheet before calling load_workbook.这样我就可以在调用 load_workbook 之前删除坏的工作表。

Thanks谢谢

This is what I came across, I dont K how to answeryour question at that level but loading workbook wise, and formatting based offof color is what I searched up and this is the code explained, I will get back to the rest of your question later when I am near my computer.这就是我遇到的问题,我不知道如何在该级别回答您的问题,但是明智地加载工作簿,并且基于颜色的格式是我搜索的内容,这是解释的代码,稍后我将回到您的其余问题当我靠近我的电脑时。

# Combining dataFrames in excel
excelName = input("Label your excel file: ")
xlsxAUTO = '.xlsx'
excelAutoNamed = excelName + xlsxAUTO
writer = pd.ExcelWriter(excelAutoNamed,engine='xlsxwriter')

Wsheet = excelAutoNamed.worksheet[1]



describe_df.to_excel(writer,sheet_name='Validation',startrow=0 , startcol=0)

header = excelAutoNamed.add_format({'bold': True, 'bottom': 2, 'bg_color': '#F9DA04'})
Wsheet.set_row(0, None, header)





df.to_excel(writer,sheet_name='Validation',startrow=len(df.columns), startcol=0)
writer.save()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM