简体   繁体   English

将一个 Excel 工作簿拆分为多个 Excel 文件

[英]splitting an Excel workbook into multiple excel files

i have an excel workbook with 29 different sheets.我有一个包含 29 个不同工作表的 Excel 工作簿。 i used the following code to save each sheet as an individual excel file:我使用以下代码将每个工作表保存为单独的 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")

i got this code from: stackoverflow.com/questions/28873252/python-splitting-an-excel-workbook .我从以下位置获得此代码: stackoverflow.com/questions/28873252/python-splitting-an-excel-workbook it worked well but is there a way i could save the workbooks by sheet name.它运行良好,但有没有办法按工作表名称保存工作簿。 so the sheet name should be what the file is called.所以工作表名称应该是文件的名称。 i tried replacing我试过更换

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

with

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

But it didnt work但它没有用

IIUC,国际大学联盟,

you can use pandas with pd.ExcelFile and read the whole workbook as a dictionary.您可以将 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM