如何创建/删除工作表而不更改.xls文件的旧工作表?

时间:2017-08-09 11:59:49

标签: python-2.7 xlrd xlsxwriter

我曾尝试使用xlsxwriter.add_worksheet()创建新工作表,但它更改了我的旧工作表。任何可以创建新工作表而不影响其他工作表的库以及如何删除.xls文件中的工作表因为我没有在xlrd或xlsxwriter中找到可以删除工作表的任何函数。

编辑:1尝试使用win32模块。能够删除工作表但无法创建新工作表而不影响现有工作表。

1 个答案:

答案 0 :(得分:1)

更新:找到答案

制作新表

import xlrd
xl_ref = xlrd.open_workbook('Path to file')

此处类型(xl_ref)是< class' xlrd.book.Book >所以当我们调用函数

xl_ref.add_sheet('Test1')

错误书对象没有属性。基本上每当我们想要操作.xls文件而不影响现有的更改时。首先,转换为工作簿对象。

from xlutils.copy import copy
xlwb_ref=copy(xl_ref)
xlwb_ref.add_sheet('Test1')
xlwb_ref.save('Path to file')

参考:Python_doc

删除工作表

    import pythoncom
    from win32com.client.gencache import EnsureDispatch
    pythoncom.CoInitialize() #if Calling same thing again and again so better reinitialize. 
    excel = EnsureDispatch("Excel.Application")
    excel_file = excel.Workbooks.Open("Path to file")
    sheet = excel.Sheets("Sheet name")
    sheet.Delete()
    excel_file.Close(True)
相关问题