我正在尝试向Excel文件ex.xls添加一个工作表,但每次添加后会删除之前创建的所有工作表。
如何在不删除其他工作表的情况下向该Excel文件添加工作表?
这是我的创建工作表的代码:
import xlwt
import xlrd
wb = Workbook()
Sheet1 = wb.add_sheet('Sheet1')
wb.save('ex.xls')
我正在尝试向Excel文件ex.xls添加一个工作表,但每次添加后会删除之前创建的所有工作表。
如何在不删除其他工作表的情况下向该Excel文件添加工作表?
这是我的创建工作表的代码:
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')
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
这是因为add_sheet函数会覆盖现有的工作表。相反,使用create_sheet函数可以解决您的问题。
ws1 = wb.create_sheet("Mysheet") # insert at the end (default)
ws2 = wb.create_sheet("Mysheet", 0) # insert at first position
ws3 = wb.create_sheet("Mysheet", -1) # insert at the penultimate position
Sheet2 = wb.add_sheet('Sheet2')
? - BruceWayne