有没有办法使用openpyxl限制字符长度?

问题描述

是否有一种方法可以使用openpyxl限制一列中的最大字符数?

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

解决方法

如何使用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)

ref:https://openpyxl.readthedocs.io/en/default/validation.html