【问题标题】:Is there a way to limit character length using openpyxl?有没有办法使用 openpyxl 限制字符长度?
【发布时间】:2020-09-22 14:06:34
【问题描述】:

有没有办法使用 openpyxl 限制一列中的最大字符数?

我知道我可以打开 excel 并通过数据验证设置字符长度限制,但我想找到一种方法来放置公式或使用 python 为单元格设置最大字符数。

【问题讨论】:

标签: python excel-formula openpyxl xlwt


【解决方案1】:

如何使用 openpyxl 限制字符长度

from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation

# Create the workbook and worksheet we'll be working with
wb = Workbook()
ws = wb.active

# Create a data-validation object with character length validation
dv = DataValidation(type="textLength",
                    operator="lessThanOrEqual"),
                    formula1=15)  # 15 characters max

# Optionally set a custom error message
dv.error ='Your entry exceeds the max character length of 15 characters'
dv.errorTitle = 'String length is too long!'

# Apply the validation to a range of cells
dv.add('B1:B1048576') # This is the same as for the whole of column B

# Add the data-validation object to the worksheet
ws.add_data_validation(dv)

参考:https://openpyxl.readthedocs.io/en/default/validation.html

【讨论】:

    猜你喜欢
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-06-08
    相关资源
    最近更新 更多