Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将数据框导出到Excel并设置列宽和文本换行_Python 3.x_Pandas_Xlsxwriter - Fatal编程技术网

Python 3.x 将数据框导出到Excel并设置列宽和文本换行

Python 3.x 将数据框导出到Excel并设置列宽和文本换行,python-3.x,pandas,xlsxwriter,Python 3.x,Pandas,Xlsxwriter,我必须将此数据框导出到Excel 将熊猫作为pd导入 导入xlsxwriter df1=pd.DataFrame(['a','b',['c','d']], 索引=[“第1行”、“第2行”], 列=['col 1'、'col 2']) df1.to_excel(os.path.join('tmp','output1.xlsx'))35; doctest:+SKIP df2=df1.copy() 使用pd.ExcelWriter(os.path.join('tmp','output2.xlsx',e

我必须将此数据框导出到Excel

将熊猫作为pd导入
导入xlsxwriter
df1=pd.DataFrame(['a','b',['c','d']],
索引=[“第1行”、“第2行”],
列=['col 1'、'col 2'])
df1.to_excel(os.path.join('tmp','output1.xlsx'))35; doctest:+SKIP
df2=df1.copy()
使用pd.ExcelWriter(os.path.join('tmp','output2.xlsx',engine='xlsxwriter')作为编写器:#doctest:+SKIP
df1.to_excel(编写器,工作表名称='sheet\u name_1')
df2.to_excel(编写器,sheet_name='sheet_name_2')

我知道“xlsxwriter”允许多种定制。如何设置列宽和文本换行,将上述代码作为草稿?

我在官方文档中找到了@jmcnamara建议的答案:

    import pandas as pd

    # Create a Pandas dataframe from some data.
    df = pd.DataFrame({'Numbers':    [1010, 2020, 3030, 2020, 1515, 3030, 4545],
                    'Percentage': [.1,   .2,   .33,  .25,  .5,   .75,  .45 ],
    })

    # Create a Pandas Excel writer using XlsxWriter as the engine.
    writer = pd.ExcelWriter("pandas_column_formats.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']

    # Add some cell formats.
    format1 = workbook.add_format({'num_format': '#,##0.00'})
    format2 = workbook.add_format({'num_format': '0%'})

    # Note: It isn't possible to format any cells that already have a format such
    # as the index or headers or any cells that contain dates or datetimes.

    # Set the column width and format.
    worksheet.set_column('B:B', 18, format1)

    # Set the format but not the column width.
    worksheet.set_column('C:C', None, format2)
上述代码摘自。

请参阅上的文档,特别是上的部分