Hello,
Some weeks ago I resolved this writing the following code:
import xlrd
import xlwt
from xlutils.copy import copy
# COPYING EXCEL SHEETS FROM DIFFERENT SOURCE FILES (.XLS) USING xlrd,
xlwt
# Parameters to fiddle with
# Source parameters
startYear = 1997
endYear = 1998
path = r'D:\My Documents\tut_python'
fileNames = [r'\COUVEN' + str(year)[2:] + 'CP.xls' for year \
in range(startYear,
endYear + 1)]
pathNames = [path + aFile for aFile in fileNames]
sourceSheetName = 'Hoja2' # Must be the same name in all files
# Target parameters
targetPath = r'D:\My Documents\tut_python'
targetFile = r'\test.xls'
# Create the target workbook
wb = xlwt.Workbook()
# Create target worksheets and copy source data
for aFile, aPath in zip(fileNames, pathNames):
# Create the target worksheet and name it
ws = wb.add_sheet(aFile[1:-6])
# Open the source book and sheet
book = xlrd.open_workbook(aPath, on_demand=True,
formatting_info=True)
# The source sheet name must be the same on all files
sheet = book.sheet_by_name(sourceSheetName)
##print sheet.cell_xf_index(0,0)
# Get number of rows and columns that contain data
numRow = sheet.nrows
numCol = sheet.ncols
for row in xrange(numRow):
# Get all the rows in the sheet (each rows is a list)
rowList = sheet.row_values(row)
for col in xrange(numCol):
# Get all the values in each list
oneValue = rowList[col]
# Copy the values to target worksheet
ws.write(row, col, oneValue)
# Save the target workbook to file
wb.save(targetPath + targetFile)
This is not how I wanted to solve it but it worked at the time. I was
able to copy the data in the sheets but of course not the formats
(even though I wanted to - I tried some things here but none worked).
Anyway, I just recently saw the thread on "copy sheet" and the code
there is much closer to what I wanted.
Kudos on these modules. I really like the speed with which they do
their work.
Thanks.