2

簡単に言えば、ある Excel ファイルの書式設定をすべて別の Excel ファイルに保存したいと考えています。ただし、formatting_info=Trueフラグを使用しているにもかかわらず、書式設定は、変更された行内の変更されていないすべてのセルに対してのみ表示されます。何かアドバイス?

import xlrd, xlutils
from xlrd import open_workbook
from xlutils.copy import copy

inBook = xlrd.open_workbook(r"path/to/file/format_input.xls", formatting_info=True, on_demand=True)
outBook = xlutils.copy.copy(inBook)

outBook.get_sheet(0).write(0,0,'changed!')
outBook.save(r"path/to/file/format_output.xls")

ここに画像の説明を入力

ここに画像の説明を入力

ここに画像の説明を入力

4

2 に答える 2

6

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")
于 2015-01-30T16:47:11.770 に答える
2

openpyxl の使用中に同様の問題が発生しました-何らかの理由で、これは利用可能なモジュールでうまく処理されないようです。以下の構文を使用して、データを入力した後、必要に応じてセルのスタイルを変更するだけになりました。

#Formatting
from openpyxl.styles import Style, Color, PatternFill, Alignment, Font, NumberFormat
#Allows for conditional formatting
from openpyxl.formatting import CellIsRule #Allows for Conditional Formatting

for cell in changed_cells:
    cell.style = Style(fill=PatternFill(patternType='solid', fgColor=Color('FFff8888')), 
                         font=Font(name="Arial",size=11), 
                         alignment=Alignment(horizontal="center"))

この種のものを xlrd で実装するための構文に関する情報は、ここにあります。

于 2015-01-30T16:49:53.060 に答える