Python xlrd / xlwt creates a new workbook using sheets from two different books preserving formatting
Let me first explain my terminology. The Excel workbook has sheets. For example. new Excel workbook contains 3 sheets by default.
Now using xlrd, xlwt and xlutils, my goal is to output a new book (say: file3) by inputting 3 sheets from file1 and 1 sheet from file2. All of this preserves as much formatting as possible. I am using the following code (file1, file2 which you have to create manually yourself, just fill them with numbers AND text):
import os
import xlrd
import xlwt
from xlutils.copy import copy as xlutils_copy
from copy import deepcopy as deep_copy
new_workbook = xlwt.Workbook()
with xlrd.open_workbook("file1.xls", formatting_info=True) as rb1:
wb1 = xlutils_copy(rb1)
allSheets = []
allSheets.append(wb1.get_sheet(0))
allSheets.append(wb1.get_sheet(1))
allSheets.append(wb1.get_sheet(2))
extra = deep_copy(wb1.get_sheet(1))
allSheets.append(extra)
allSheets[-1].name = 'extra sheet file1'
with xlrd.open_workbook("file2.xls", formatting_info=True) as rb2:
wb2 = xlutils_copy(rb2)
extra2 = deep_copy(wb2.get_sheet(0))
allSheets.append(extra2)
allSheets[-1].name = 'extra sheet file2'
new_workbook._Workbook__worksheets = allSheets
outputFile = "file3.xls"
new_workbook.save(outputFile)
os.startfile(outputFile)
The problem is that when I open my file3.xls file, I get an error message given by Excel: "File error: data might be lost." By clicking OK and checking the file, I see a lot of #CURRENCIES! errors, column width, etc., but the font and colors were not. It's great that the numbers were copied perfectly, but the text doesn't. Does anyone know what is going wrong?
source to share
No one has answered this question yet
See similar questions:
or similar: