使用 pandas 和 xlsxwriter 在 excel 中增加不同工作表上的列宽

Increase width of columns on different sheets in excel using pandas and xlsxwriter

我正在尝试使用 pandasxlsxwriter 在 excel 文件的不同工作表中写入数据。我的代码如下。

import pandas as pd


# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [111231231, 123243244, 131231231, 142131231]})
df2 = pd.DataFrame({'Data': [211232131, 2212312322, 2323212213, 2412312312]})
df3 = pd.DataFrame({'Data': [31123123311, 32345225245, 332542355432, 342435245245]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_multiple.xlsx', engine='xlsxwriter')

# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')

# Close the Pandas Excel writer and output the Excel file.
writer.save()

我正在不同的工作表上打印所有数据框,并希望将列的宽度设置多一点。

我阅读了文档,命令 writer.set_column() 对我不起作用。如果有人在这方面帮助我,我将不胜感激

请按以下方式尝试。例如,我只为 'Sheet1' 设置了 column_width。 如果需要,您可以尝试其他 Sheet。另外,我打算通过 'idx' 设置一列,这样您就可以指定要更改哪一列的宽度。在您的情况下,这并不重要,因为只有一列,但以防万一您可能有多个列。 氪

import pandas as pd


# Create some Pandas dataframes from some data.
df1 = pd.DataFrame({'Data': [111231231, 123243244, 131231231, 142131231]})
df2 = pd.DataFrame({'Data': [211232131, 2212312322, 2323212213, 2412312312]})
df3 = pd.DataFrame({'Data': [31123123311, 32345225245, 332542355432, 342435245245]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('./pandas_multiple.xlsx', engine='xlsxwriter')

# Write each dataframe to a different worksheet.
df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet2')
df3.to_excel(writer, sheet_name='Sheet3')

# set column width for 'Sheet1'. If need do the same for other Sheet 
column_width = 30
worksheet = writer.sheets['Sheet1']
idx = 1
worksheet.set_column(idx, idx, column_width)
    
    
# Close the Pandas Excel writer and output the Excel file.
writer.save()