我正在为 xlutils、xlrd 和 xlwt 创建一个名为 excel 函数的类,我最终可能会创建一个库。如果您有兴趣帮助我尝试制作删除工作表功能。
您可能想要转向 openpyxl 和/或 pyexcel,因为它们更容易并且具有此功能。
以下是使用 openpyxl 进行复制的方法: 使用 openpyxl复制整个工作表
这是 pyexcel 的文档,它是 xlwt、xlrd 和 xlutils 的包装器:https ://pyexcel.readthedocs.io/en/latest/
如果要从一个 Excel 工作簿中提取数据并输出到另一个工作簿,则需要使用 createCopy(original workbook, other workbook, original filename, new filename)
import xlwt
import xlrd
import xlutils.copy
import xlutils class excelFunctions():
def getSheetNumber(self, fileName, sheetName):
# opens existing workbook
workbook = xlrd.open_workbook(fileName, on_demand=True)
#turns sheet name into sheet number
for index, sheet in enumerate(workbook.sheet_names()):
if sheet == sheetName:
return index
def createSheet(self, fileName, sheetName):
# open existing workbook
rb = xlrd.open_workbook(fileName, formatting_info=True, on_demand=True)
# make a copy of it
wb = xl_copy(rb)
# creates a variable called sheets which stores all the sheet names
sheets = rb.sheet_names()
# creates a string which is equal to the sheetName user input
str1 = sheetName
# checks to see if the given sheetName is a current sheet
if (str1 not in sheets):
# add sheet to workbook with existing sheets
Sheet = wb.add_sheet(sheetName)
# save the sheet with the same file name as before
wb.save(fileName)
else:
# this declares the sheet variable to be equal to the sheet name the user gives
sheet = wb.get_sheet(self.getSheetNumber(fileName, sheetName))
# save the sheet with the same file name as before
wb.save(fileName)
def createCopy(self, fileName, fileName2, sheetName, sheetName2):
# open existing workbook
rb = xlrd.open_workbook(fileName, formatting_info=True)
# defines sheet as the name of the sheet given
sheet = rb.sheet_by_name(sheetName)
# makes a copy of the original sheet
wb = xl_copy(rb)
# creates an int called column_count which is equal to the sheets maximum columns
column_count = sheet.ncols - 1
# creates a blank array called stuff
Stuff = []
# this loops through adding columns from the given sheet name
for i in range (0, column_count):
Stuff.append([sheet.cell_value(row, i) for row in range(sheet.nrows)])
# create a sheet if there is not already a sheet
self.createSheet(fileName, sheetName2)
# defines sheet as the new sheet
sheet = wb.get_sheet(self.getSheetNumber(fileName, sheetName2))
# this writes to the sheet
for colidx, col in enumerate(Stuff):
for rowidx, row in enumerate(col):
sheet.write(rowidx, colidx, row)
# this saves the file
wb.save(fileName2)