3 回答

TA貢獻1828條經驗 獲得超3個贊
這將打印第 1 行的所有內容;
list_with_values=[]
for cell in ws[1]:
list_with_values.append(cell.value)
如果出于某種原因想要獲取已填寫的列字母的列表,則可以:
column_list = [cell.column for cell in ws[1]]
對于你的第二個問題;假設您已將標題值存儲在名為“list_with_values”的列表中
from openpyxl import Workbook
wb = Workbook()
ws = wb['Sheet']
#Sheet is the default sheet name, you can rename it or create additional ones with wb.create_sheet()
ws.append(list_with_values)
wb.save('OutPut.xlsx')

TA貢獻1900條經驗 獲得超5個贊
只讀模式提供對工作表中任何一行或一組行的快速訪問。使用該方法iter_rows()限制選擇。因此,要獲得工作表的第一行:
rows = ws.iter_rows(min_row=1, max_row=1) # returns a generator of rows
first_row = next(rows) # get the first row
headings = [c.value for c in first_row] # extract the values from the cells

TA貢獻1817條經驗 獲得超14個贊
查理·克拉克斯(Charlie Clarks)的答案精簡到具有列表理解力
headers = [c.value for c in next(wb['sheet_name'].iter_rows(min_row=1, max_row=1))]
添加回答
舉報