[英]Renaming sheets in Excel using Python; referencing cell value for sheet name
I have been working on a project using Python to build a program that simplifies changes to be made in Microsoft Excel. 我一直在使用Python构建一个可简化Microsoft Excel中所做更改的程序的项目。 I am attempting to loop through a workbook to rename all of the sheets.
我试图遍历工作簿以重命名所有工作表。 The main difference my problem has from what I have read is that I am renaming the sheets based on a value in a cell using the following code:
我的问题与所读内容的主要区别在于,我正在使用以下代码根据单元格中的值重命名工作表:
"""Loop through each worksheet and rename the sheet using a value from the sheet."""
for i in wb:
ws = wb.active
c = ws['A1']
ws.title = c + (i + 1)
print(sheet.title)
If someone could clarify what the issue is I would greatly appreciate your assistance. 如果有人可以澄清问题所在,我们将不胜感激。 I received the following error report:
我收到以下错误报告:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "C:\Users\Que\AppData\Local\Programs\Python\Python37-32\lib\site-packages\openpyxl\workbook\child.py", line 93, in title
m = INVALID_TITLE_REGEX.search(value)
TypeError: expected string or bytes-like object
I am using Powershell interactive mode to test each piece of code. 我正在使用Powershell交互模式来测试每段代码。 Please understand I am attempting to access a value in a cell and have made several attempts to change the code to reflect my objective.
请理解我正在尝试访问单元格中的值,并且已经尝试过几次更改代码以反映我的目标。 Your insight and observations are appreciated.
感谢您的见解和观察。
Maybe the code below will solve the problem: 也许下面的代码可以解决问题:
for sheet in wb:
sheet_name = sheet.title
first_cell_value = str(sheet['A1'].value)
sheet.title = first_cell_value + sheet_name + "1"
print(sheet.title)
This way you are: 这样,您就是:
first_cell_value + sheet_name + "1"
; first_cell_value + sheet_name + "1"
; The error report you are getting is because you are trying to use the cell itself ( c
) instead of the value inside of it ( c.value
) to rename your worksheet, and the cell itself is not a string/byte-like object. 您收到的错误报告是因为您试图使用单元格本身(
c
)而不是其中的值( c.value
)重命名工作表,并且该单元格本身不是一个类似于字符串/字节的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.