Ty *_*man 2 python excel openpyxl
我该如何找回
City,Population,Country在下面的示例表City,Population,Country,从表1帧和其他列名从所有其他工作表Excel工作表示例:
| City | Population | Country |
| -----------|------------ | ------------ |
| Madison | 252,551 | USA |
| Bengaluru | 10,178,000 | India |
| ... | ... | ... |
Run Code Online (Sandbox Code Playgroud)
示例代码:
from openpyxl import load_workbook
wb = load_workbook(filename=large_file.xlsx, read_only=True)
sheet = wb.worksheets[0]
... (not sure where to go from here)
Run Code Online (Sandbox Code Playgroud)
笔记:
只读模式提供对工作表中任何行或行集的快速访问。使用方法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
Run Code Online (Sandbox Code Playgroud)
这将打印第1行中的所有内容;
list_with_values=[]
for cell in ws[1]:
list_with_values.append(cell.value)
Run Code Online (Sandbox Code Playgroud)
如果出于某种原因要获取已填写的列字母的列表,则可以:
column_list = [cell.column for cell in ws[1]]
Run Code Online (Sandbox Code Playgroud)
关于第二个问题;假设您已将标头值存储在名为“ 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')
Run Code Online (Sandbox Code Playgroud)
小智 5
查理·克拉克(Charlie Clarks)的答案通过列表理解压缩为一行
headers = [c.value for c in next(wb['sheet_name'].iter_rows(min_row=1, max_row=1))]
Run Code Online (Sandbox Code Playgroud)