python xlrd/xlwt create new workbook using sheets from 2 different workbooks preserving formatting

3.2k Views Asked by At

First let me explain my terminology. An Excel workbook has sheets. E.g. a new Excel workbook contains by default 3 sheets.

Now, using xlrd, xlwt and xlutils, my purpose is to output a new workbook (say: file3) with as input 3 sheets from file1 and 1 sheet from file2. This all preserving formatting as much as possible. I am using the following code (file1, file2 you have to create manually by 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 when I open my 'file3.xls' I end up with an error given by Excel: 'File error: data may have been lost.' Clicking 'OK' and inspecting the file, I see a lot of #VALUE! errors, the column width etc. has been preserved, however the font and colors have not. Remarkable is that numbers have been copied perfectly, but text has not. Does anyone have a clue what is going wrong?

0

There are 0 best solutions below