![](/img/trans.png)
[英]Copying value of cell (X,Y) to cell (A,B) in same sheet of an Excel file using Python
[英]Renaming sheets in Excel using Python; referencing cell value for sheet name
我一直在使用Python構建一個可簡化Microsoft Excel中所做更改的程序的項目。 我試圖遍歷工作簿以重命名所有工作表。 我的問題與所讀內容的主要區別在於,我正在使用以下代碼根據單元格中的值重命名工作表:
"""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)
如果有人可以澄清問題所在,我們將不勝感激。 我收到以下錯誤報告:
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
我正在使用Powershell交互模式來測試每段代碼。 請理解我正在嘗試訪問單元格中的值,並且已經嘗試過幾次更改代碼以反映我的目標。 感謝您的見解和觀察。
也許下面的代碼可以解決問題:
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)
這樣,您就是:
first_cell_value + sheet_name + "1"
; 您收到的錯誤報告是因為您試圖使用單元格本身( c
)而不是其中的值( c.value
)重命名工作表,並且該單元格本身不是一個類似於字符串/字節的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.