0
我有一個Python 2.7腳本,可以轉換各種數據並通過OpenPyXL 2.4.5將它輸出到XLSX。目前我正在遍歷所有單元格,我使用「max_row」和「max_column」縮小了這些單元格的大小。這對我來說看起來不是很快或很有效。什麼是設置以下最快的方法?如果你能提出一般的方法論,我將不勝感激。以下粗略基準測試適用於Windows 7 SP1 x64,配備16 GB RAM和Intel [email protected] GHz。格式化最快的方法
- 邊框(格式化35880個細胞花費40秒。)
- 字體和對齊(格式化35880個細胞需要42s中。)
- 底紋(格式化35880個細胞需要28S)
- 隱藏未使用的行/列(隱藏16,380列×1,039,606行需要很多分鐘,僅隱藏列需要0.2秒。)
以下是迭代方法。
def format_xlsx(csv_list, ws_to_format):
""" Use OpenPyXL to format a XLSX. """
process_start = timer()
for row in csv_list:
count = count + 1
ws_to_format.append(row)
row_count = ws_to_format.max_row
column_count = ws_to_format.max_column
for y_axis in range(1, column_count+1):
for x_axis in range(1, row_count+1):
ws_to_format = xlsx_borders(ws_to_format, x_axis, y_axis)
ws_to_format = xlsx_shading(ws_to_format, x_axis, y_axis)
ws_to_format = xlsx_font_and_alignment(ws_to_format, x_axis, y_axis)
ws_to_format = xlsx_hide_unused_colrow(ws_to_format)
return
以下是隱藏未使用的行/列的方法。
def xlsx_hide_unused_colrow(ws_to_format):
row_count = ws_to_format.max_row
column_count = ws_to_format.max_column
start_range = column_number_to_letter(column_count+2)
end_range = column_number_to_letter(16384)
ws_to_format.column_dimensions.group(start_range, end_range, hidden=True)
start_range = row_count+2
for y in xrange(start_range, 1048577):
ws_to_format.row_dimensions[y].hidden=True
- 感謝指針。我是Python新手,所以請原諒這個問題是否愚蠢,但是我沒有在for循環之外指定「max_row」/「max_column」嗎? – Burzin
您可以在嵌套函數中調用max_column,並在for循環中調用該函數。 –