首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将pandas数据框导出到Excel并设置列宽和文本换行

将pandas数据框导出到Excel并设置列宽和文本换行
EN

Stack Overflow用户
提问于 2019-05-16 13:19:42
回答 1查看 3.2K关注 0票数 0

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

代码语言:javascript
运行
复制
    import pandas as pd
    import xlsxwriter
    df1 = pd.DataFrame([['a', 'b'], ['c', 'd']],
                    index=['row 1', 'row 2'],
                    columns=['col 1', 'col 2'])

    df1.to_excel(os.path.join('tmp', "output1.xlsx"))  # doctest: +SKIP
    df2 = df1.copy()
    with pd.ExcelWriter(os.path.join('tmp', "output2.xlsx"), engine='xlsxwriter') as writer:  # doctest: +SKIP
        df1.to_excel(writer, sheet_name='Sheet_name_1')
        df2.to_excel(writer, sheet_name='Sheet_name_2')

我知道'xlsxwriter‘允许多个自定义。以上述代码为草稿,如何设置列宽和文本换行?

EN

回答 1

Stack Overflow用户

发布于 2019-05-17 01:11:46

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

代码语言:javascript
运行
复制
    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)

上面的代码取自https://xlsxwriter.readthedocs.io/example_pandas_column_formats.html#ex-pandas-column-formats

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56161318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档