将 sheet 添加到现有 excel 工作 sheet 而不删除其他 sheet

Adding a sheet to an existing excel worksheet without deleting other sheet

我正在尝试将 sheet 添加到 excel 文件:ex.xls,每当我这样做时,它都会删除所有以前制作的 sheet。

如何在不删除其他 sheet 的情况下向此 excel 文件添加 sheet?

这是我创建 sheet:

的代码
import xlwt
import xlrd

wb = Workbook()
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')

我相信这是做你想做的唯一方法:

import xlrd, xlwt
from xlutils.copy import copy as xl_copy

# open existing workbook
rb = xlrd.open_workbook('ex.xls', formatting_info=True)
# make a copy of it
wb = xl_copy(rb)
# add sheet to workbook with existing sheets
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')

下面是使用 "openpyxl" 在 excel 工作簿中创建一个新的 sheet。

import openpyxl

wb=openpyxl.load_workbook("Example_Excel.xlsx")
wb.create_sheet("Sheet1")  

如果 sheets 或工作簿尚不存在,您将得到一个错误,以避免这种情况

import openpyxl

wb=openpyxl.load_workbook("Example_Excel.xlsx")
try:
    wb["Sheet1"]
except:
    wb.create_sheet("Sheet1") 

根据您的使用方式,下面是将信息写入多个页面的示例

import openpyxl

work_book = 'Example_Excel.xlsx'
sheets = "Sheet1","Sheet2","Sheet3","Sheet4","Sheet5"

for current_sheet in sheets:
    wb=openpyxl.load_workbook(work_book)

    #if the sheet doesn't exist, create a new sheet
    try:
      wb[current_sheet]
    except:
      wb.create_sheet(current_sheet) 

    #wait for user to press "Enter" before starting on next sheet
    raw_input("Press Enter to continue...")

#The code for you wish repeated for each page
    #This example will print the sheet name to "B2" cell on that sheet
    cell ="B"+str(2)
    sheet=wb[current_sheet]
    sheet[cell].value= current_sheet