python openpyxl Filtering Some Columns
- 2021-09-24 23:14:40
- OfStack
Because you want to copy some cell formats of excel, you need to select the eligible
The following example is a reservation less than 15
Then in the new form
wbsheet_new.merge_cells(cell2)
wbsheet_new is the new form, and cell2 is the cell reserved after filtering, which is expressed in the format of I24: J24, K24: L24
The result of screening is [('AO', 'AP')], which is the expression mode of list containing tuples, and then the first element is extracted by result [0] [0].
If it is larger than 15 columns
column_index_from_string(result[0][0])>=15
Remove it and keep the rest
from openpyxl.utils import get_column_letter, column_index_from_string
import re
s=['AK23:AL23',
'AM23:AN23',
'AO23:AP23',
'AQ23:AR23',
'B24:C24',
'D24:F24',
'G24:H24',
'I24:J24',
'K24:L24',
'M24:N24',
'Q24:R24',
'S24:U24',
'V24:W24',
'X24:Y24',
'Z24:AA24',
'AB24:AC24',
'AF24:AG24',
'AH24:AJ24',
'AK24:AL24',
'AM24:AN24',
'AO24:AP24',]
for si in s:
result=re._compile(r'(\w+?)\d+:(\w+?)\d+',flags=0).findall(si)
print (result)
if column_index_from_string(result[0][0])>=15:
print(' Remove %s'%result[0][0])
Supplement: python openpyxl Get the list of merged cells, filter and unmerge cells
The code is as follows:
# Gets the information of all merged cells in the table and traverses
for i in ws.merged_cell_ranges:
# Gets the starting row, column, ending row, column of the merged cell
r1, r2, c1, c2 = i.min_row, i.max_row, i.min_col, i.max_col
# Unmerge
ws2.unmerge_cells(start_row = r1, end_row = r2, start_column = c1, end_column = c2)