简体   繁体   中英

OpenPyXL set number_format for the whole column

I'm exporting some data to Excel and I've successfully implemented formatting each populated cell in a column when exporting into Excel file with this:

import openpyxl
from openpyxl.utils import get_column_letter

wb = openpyxl.Workbook()
ws = wb.active

# Add rows to worksheet
for row in data:
    ws.append(row)

# Disable formatting numbers in columns from column `D` onwards
#   Need to do this manually for every cell
for col in range(3, ws.max_column+1):
    for cell in ws[get_column_letter(col)]:
        cell.number_format = '@'

# Export data to Excel file...

But this only formats populated cells in each column. Other cells in this column still have General formatting.

How can I set all empty cells in this column as @ so that anyone, who will edit cells in these columns within this exported Excel file, will not have problems with inserting lets say phone numbers as actual Numbers.

For openpyxl you must always set the styles for every cell individually. If you set them for the column, then Excel will apply them when it creates new cells, but styles are always still applied to individual cells.

As you are iterating on the rows of that columns only to the max_cell those are the only cells that are being reformatted. While you can't reformat a column you can use a different way to set the format at least to a specific cell:

last_cell = 100

for col in range(3, ws.max_column+1):
    for row in range(1, last_cell):
        ws.cell(column=col, row=row).number_format = '@'  # Changing format to TEXT

The following will format all the cell in the column up to last_cell you can use that, and, while it's not exactly what you need it's close enough.

conditional formatting will do the hack to put number formatting on the entire column. for applying thousand separator on entire column this worked for me:

diff_style = DifferentialStyle(numFmt = NumberFormat(numFmtId='4',formatCode='#,##0.00'))
rule1 = Rule(type="expression", dxf=diff_style)
rule1.formula = ["=NOT(ISBLANK($H2))"]  // column on which thousand separator is to be applied
work_sheet.conditional_formatting.add("$H2:$H500001", rule1)  // provide a range of cells

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM