如何找回
City
、Population
、Country
City
、Population
、Country
、工作表 1 中的框架以及所有其他工作表中的其他列名称Excel 工作表示例:
| City | Population | Country |
| -----------|------------ | ------------ |
| Madison | 252,551 | USA |
| Bengaluru | 10,178,000 | India |
| ... | ... | ... |
示例代码:
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)
备注:
这将打印第 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')
只读模式提供对工作表中任何行或行集的快速访问。使用
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
查理·克拉克 (Charlie Clarks) 的答案通过列表理解压缩为一行
headers = [c.value for c in next(wb['sheet_name'].iter_rows(min_row=1, max_row=1))]
我就是这样处理的
from openpyxl.utils import get_column_letter
def get_columns_from_worksheet(ws):
return {
cell.value: {
'letter': get_column_letter(cell.column),
'number': cell.column - 1
} for cell in ws[1] if cell.value
}
使用的一个例子是
from openpyxl import load_workbook
wb = load_workbook(filename='my_file.xlsx')
ws = wb['MySheet']
COLUMNS = get_columns_from_worksheet(ws)
for cell in ws[COLUMNS['MY Named Column']['letter']]:
print(cell.value)
同时捕获字母和数字代码的主要原因是因为 openpyxl 中的不同函数和模式使用数字或字母,因此参考两者是非常有价值的
如何检索 openpyxl 只读工作簿中的所有列名称
假设文件名是“large_file.xlsx”并且数据位于第一张纸上(索引= 0),我会做这样的事情(在Python 3.12和openpyxl 3.1.2中测试):
您可以迭代第一行单元格 (
sheet.iter_rows()
):
from openpyxl import load_workbook
workbook = load_workbook(filename='large_file.xlsx', data_only=True)
sheet = workbook.worksheets[0]
headers = [cell.value for cell in next(sheet.iter_rows(min_row=1, max_row=1))]
print(headers)
或只需选择第一行 (
sheet[int]
):
workbook = load_workbook(filename='large_file.xlsx', data_only=True)
sheet = workbook.worksheets[0]
headers = [cell.value for cell in sheet[1]]
print(headers)