将工作表添加到现有Excel工作表而不删除其他工作表

时间:2016-06-28 16:32:38

标签: excel python-2.7 csv xlrd xlwt

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

如何在不删除其他工作表的情况下将工作表添加到此Excel文件中?

以下是我创建工作表的代码:

import xlwt
import xlrd

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

2 个答案:

答案 0 :(得分:6)

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

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')

答案 1 :(得分:1)

以下是使用" openpyxl"在Excel工作簿中创建新工作表。

import openpyxl

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

如果工作表或工作簿尚不存在,则会出现错误,以避免出现此错误

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