我想知道在使用 XlsxWriter 时是否有一种方法可以通过名称而不是列字母或索引来引用列,以防列索引发生更改,但我仍然希望将格式应用于同一列,即使其位置发生变化。
我还预先将数据框的内容导出到 Excel 文件,因此如果有一种方法可以使用 Pandas 引用该列,然后将该引用分配给在 XlsxWriter 方法中的列引用所在位置调用的变量,那么也可以工作。
而不是这个:
df.to_excel(writer, sheet_name='RCM_Output',index = False)
worksheet.data_validation(A1:A500, {'validate': 'list',
'source': ['blocked', 'unblocked']})
是否可以编写某种动态变量来代替硬编码的单元格引用?
df.to_excel(writer, sheet_name='RCM_Output',index = False)
worksheet.data_validation('Block Status':1:500, {'validate': 'list',
'source': ['blocked', 'unblocked']})
最佳答案
最好的方法是使用 data_validation()
的行/列表示法,并使用 Pandas 获取列的索引和数据帧的维度。像这样的事情:
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame(
{
"Data 1": [10, 20, 30, 20],
"Data 2": [10, 20, 30, 20],
"Block Status": ["unblocked", "blocked", "unblocked", "unblocked"],
"Data 3": [10, 20, 30, 20],
"Data 4": [10, 20, 30, 20],
}
)
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_example.xlsx", engine="xlsxwriter")
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name="Sheet1")
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets["Sheet1"]
# Get the max row from the dimensions of the dataframe.
row_num = df.shape[0]
# Get the column index from the name. We add 1 to account for the index.
# If the index is turned off then this can be omitted.
col_num = 1 + df.columns.get_loc("Block Status")
# Add the data validation based on these dimensions.
worksheet.data_validation(
1, col_num, row_num, col_num,
{
"validate": "list",
"source": ["blocked", "unblocked"]
},
)
# Close the Pandas Excel writer and output the Excel file.
writer.close()
输出:
关于excel - Python - XlsxWriter : Referring to columns by column name, 不是列字母(硬编码与动态变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75722640/