在 pandas 中,可以使用工作表第一行中指定的名称来访问 Excel 列。在 xlwings 中如何实现这一点?
从 xlwings 0.7.0 开始,您可以使用 Pandas 作为转换器。对于这样的示例工作簿:
A B C
1 4 7
2 5 8
3 6 9
此代码将读取表格并允许您通过列标题访问数据。关键是
.options(pd.DataFrame, index=False)
位。该特定调用将返回一个带有默认索引的 Pandas DataFrame。
有关 xlwings 转换器的更多信息此处。
import xlwings as xw
import pandas as pd
def calc():
# Create a reference to the calling Excel xw.Workbook
wb = xw.Workbook.caller()
table = xw.Range('A1').table.options(pd.DataFrame, index=False).value
# Access columns as attributes of the Pandas DataFrame
print table.A
print table.B
# Access columns as column labels of the Pandas DataFrame
print table['A']
print table['B']
if __name__ == '__main__':
path = "test.xlsm"
xw.Workbook.set_mock_caller(path)
calc()
您可以使用方括号访问列,如建议此处:
import xlwings as xw
wb = xw.Workbook.active()
xw.Range('TableName[ColumnName]').value
这是仅使用
xlwings
python 库而不提供表名称的答案:
import xlwings as xw
#load excelfile
workbook = xw.Book('name_of_excelfile.xlsx')
#get data from sheet "sheet_name" in "name_of_excelfile.xlsx" workbook
sheet = workbook.sheets['Sheet1']
#store first row(header row) data in a list
header_row = sheet.range('1:1').value
#get index of column named "column_name" from header_row list
column_index = header_row.index('column_name') + 1
#get excel column letter from index of column
column_letter = xw.utils.col_name(column_index)
#get the data of column "column_name" as a list
column_data = sheet.range(f'{column_letter}2').expand('down').value
我认为目前最有效的方法是使用:
import xlwings as xw
wb = xw.Book("test.xlsx")
ws = wb.sheets[0]
a_col = ws[ws["1:1"].api.Find("column_name").Address].expand("down")
print(a_col.value)
尽管如果能够实现
a_col
的单个函数就好了(对应于 pandas中的
df["column_name"]
)。