xlwt.write
スタイル情報を 3 番目の引数として受け入れます。残念ながら、xlrd と xlwt は 2 つの非常に異なる XF オブジェクト形式を使用します。xlrd
したがって、セルのスタイルを で読み取ったブックからで作成したブックに直接コピーすることはできませんxlwt
。
回避策は、 を使用してファイルをコピーし、そのxlutils.XLWTWriter
オブジェクトのスタイル情報を取得して、更新するセルのスタイルを保存することです。
まず、非常によく似た質問で提供されている John Machin によるパッチ機能が必要です。
from xlutils.filter import process,XLRDReader,XLWTWriter
#
# suggested patch by John Machin
# https://stackoverflow.com/a/5285650/2363712
#
def copy2(wb):
w = XLWTWriter()
process(
XLRDReader(wb,'unknown.xls'),
w
)
return w.output[0][1], w.style_list
次に、メインコードで:
import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy
inBook = xlrd.open_workbook(r"/tmp/format_input.xls", formatting_info=True, on_demand=True)
inSheet = inBook.sheet_by_index(0)
# Copy the workbook, and get back the style
# information in the `xlwt` format
outBook, outStyle = copy2(inBook)
# Get the style of _the_ cell:
xf_index = inSheet.cell_xf_index(0, 0)
saved_style = outStyle[xf_index]
# Update the cell, using the saved style as third argument of `write`:
outBook.get_sheet(0).write(0,0,'changed!', saved_style)
outBook.save(r"/tmp/format_output.xls")