看着冰糖

【Python】Excel基本操作 -- 写(pandas)

刚开始使用,故未考虑表格、单元格及字体样式

参考:https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html#pandas.ExcelWriter

def test_create():
    """
    1.创建3个DataFrame,并将其为3个表单写入fortest.xlsx文件;
    2.拷贝创建一个DataFrame并保存
    :return:
    """
    df_by_column = pd.DataFrame({'species': ['bear', 'bear', 'marsupial'], 'population': [1864, 22000, 80000]}, index=['panda', 'polar', 'koala'])
    df_by_row = pd.DataFrame([[1, 2], [4, 5], [7, 8]], index=['cobra', 'viper', 'sidewinder'], columns=['max_speed', 'shield'])
    df_ignore_idx = pd.DataFrame(columns=['问题单号', '当前状态', '责任人'], data=[
        ['DTS20200930101132100', '开发人员分析修改', '张哒哒'],
        ['DTS20200930101132101', '项目经理定位', '徐晓晓'],
        ['DTS20201010121221217', '测试人员回归测试', '于聪聪'],
        ['DTS20201006151614011', '开发人员分析修改', '张哒哒']
    ])

    print('------------df_by_column')
    print(df_by_column)
    print('------------df_by_row')
    print(df_by_row)
    print('------------df_ignore_idx')
    print(df_ignore_idx)

    with pd.ExcelWriter(path='fortest.xlsx', mode='w') as ew:
        # sheet_name--起个名字,避免覆盖;因为后面每一个都默认是'Sheet1'
        df_by_row.to_excel(ew, sheet_name='df_by_row')
        # index_label--写入时为索引列设置列名
        df_by_column.to_excel(ew, sheet_name='df_by_column', index_label='name')
        df_ignore_idx.to_excel(excel_writer=ew, sheet_name='df_ignore_idx')

        df_dts = df_ignore_idx.copy()
        # index--写入时忽略索引
        df_dts.to_excel(excel_writer=ew, sheet_name='DTS', index=False, encoding='UTF-8')

PyCharm Console:

posted on 2020-10-09 21:48  看着冰糖  阅读(369)  评论(0编辑  收藏  举报

导航