【问题标题】:OpenPyXL set number_format for the whole columnOpenPyXL 为整列设置 number_format
【发布时间】:2020-05-26 14:34:32
【问题描述】:

我正在将一些数据导出到 Excel,并且在导出到 Excel 文件时,我已经成功地实现了对列中每个填充单元格的格式设置:

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...

但这只会格式化每列中填充的单元格。此列中的其他单元格仍然具有General 格式。

如何将此列中的所有空单元格设置为@,以便在此导出的 Excel 文件中编辑这些列中的单元格的任何人在插入电话号码作为实际数字时不会遇到问题。

【问题讨论】:

    标签: python django excel openpyxl


    【解决方案1】:

    当您仅将这些列的行迭代到 max_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
    

    以下内容会将列中的所有单元格格式化为last_cell,您可以使用它,虽然它并不完全符合您的需要,但它足够接近。

    【讨论】:

    • 这样就可以了,谢谢。我只是将行范围更改为将某些行填充到现有行数,例如ws.max_row+100,因此任何要添加新行的人都会自动格式化单元格。
    【解决方案2】:

    对于 openpyxl,您必须始终为每个单元格单独设置样式。如果为列设置它们,则 Excel 将在创建新单元格时应用它们,但样式始终仍应用于单个单元格。

    【讨论】:

      【解决方案3】:

      条件格式可以将数字格式放在整个列上。对于在整个列上应用千位分隔符,这对我有用:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-17
        • 2015-10-28
        • 2022-06-10
        • 2020-02-17
        相关资源
        最近更新 更多