导出特定的工作表,并保存其他文件openpyxl [英] Export specific Sheet, and save different file openpyxl

查看:192
本文介绍了导出特定的工作表,并保存其他文件openpyxl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从excel文件中导出特定工作表,但没有结果.我想将一张特定的纸导出到一个全新的文件中,我写的是:

I'm trying to export a specific sheet from an excel file, but without a result. I want to export a specific sheet of paper to a completely new file What I have written is:

import openpyxl
book = openpyxl.load_workbook('C:\Python\test.xlsx')
a = (book.get_sheet_names())
sheet1 = book[a[5]]
sheet1.save('C:\Python\sheet2.xlsx')

另外,我做不到的另一件事是,如果我有名字,就找一张纸.

Also, another thing I can't do,and look for a certain sheet if I have its name.

如果问题很简单,我深表歉意,但是距我开始使用python已经有几天了:)

I apologize if the questions are simple, but it's been a few days since I started with python :)

推荐答案

openpyxl确实提供了copy_worksheet(),但不能在不同的工作簿之间使用.您可以逐单元复制工作表,也可以在内存中修改起始工作簿,然后可以使用其他文件名进行保存.这是代码

Well, openpyxl does provide copy_worksheet() but it cannot be used between different workbooks. You can copy your sheet cell-by-cell or you can modify your starting workbook in memory and then you can save it with a different file name. Here is the code

import openpyxl

# your starting wb with 2 Sheets: Sheet1 and Sheet2
wb = openpyxl.load_workbook('test.xlsx')

sheets = wb.sheetnames # ['Sheet1', 'Sheet2']

for s in sheets:

    if s != 'Sheet2':
        sheet_name = wb.get_sheet_by_name(s)
        wb.remove_sheet(sheet_name)

# your final wb with just Sheet1
wb.save('test_with_just_sheet2.xlsx')

这篇关于导出特定的工作表,并保存其他文件openpyxl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆