excel - Python - XlsxWriter : Referring to columns by column name, 不是列字母(硬编码与动态变量)

标签 excel dataframe variables dynamic xlsxwriter

我想知道在使用 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()

输出:

enter image description here

关于excel - Python - XlsxWriter : Referring to columns by column name, 不是列字母(硬编码与动态变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75722640/

相关文章:

python - 一种仅针对频繁值的热编码

python - 如何在连接时合并大型数据框并消除不相关的列?

c++ - 检查cpp文件中是否使用了变量

sql - pyspark.sql.functions.window 函数的 'startTime' 参数和 window.start 有什么作用?

python:将变量值插入变量名

python - 如何在 web.py 中跨请求保持变量值

excel - 如何在VBA代码中设置可变的列宽

php - 为什么我的 Excel 文件无法使用 PHP 打开?

vba - 启动 Windows 资源管理器并突出显示文件

vba - 根据 ComboBox 值自动复制和粘贴特定列