【问题标题】:splitting an Excel workbook into multiple excel files将 Excel 工作簿拆分为多个 Excel 文件
【发布时间】:2020-02-25 19:52:40
【问题描述】:

我有一个包含 29 个不同工作表的 Excel 工作簿。我使用以下代码将每张工作表另存为单独的 excel 文件:

from xlrd import open_workbook
from xlwt import Workbook

rb = open_workbook('c:\\original file.xls',formatting_info=True)

for a in range(5): #for example there're only 5 tabs/sheets
    rs = rb.sheet_by_index(a)

    new_book = Workbook()
    new_sheet = new_book.add_sheet('Sheet 1')

    for row in range(rs.nrows):
        for col in range(rs.ncols):
            new_sheet.write(row, col, rs.cell(row, col).value)

    new_book.save("c:\\" + str(a) + ".xls")

我从以下地址获得此代码:stackoverflow.com/questions/28873252/python-splitting-an-excel-workbook。它运作良好,但有没有办法可以按工作表名称保存工作簿。所以工作表名称应该是文件的名称。我尝试替换

new_book.save("c:\\" + str(a) + ".xls")

new_book.save(sheet.names + str(a) + ".xls")

但是没用

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    IIUC,

    您可以将 pandas 与 pd.ExcelFile 一起使用,并将整个工作簿作为字典来阅读。

    import pandas as pd
    
    xl = pd.ExcelFile('c:\\original file.xls')
    
    
    for sheet in xl.sheet_names:
        df = pd.read_excel(xl,sheet_name=sheet)
        df.to_excel(f"{sheet}.xls",index=False)
    

    【讨论】:

    • 如果我没有在 df_to_excel 上指定,它应该保存在哪里?
    • 它保存到脚本的路径,您可以通过在{sheet}@Tamarie之前附加来更改它
    • 工作完美。
    • 错误答案,它会破坏格式
    • @DemetryPascal 是的,这是真的,如果你想保留或保留格式,你需要使用像 xlwings 这样的库。我知道痛苦
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多