import xlwt
wb = xlwt.Workbook()
ws = wb.add_sheet('Test')
# 陷阱1:大整数可能被自动转换为浮点数
ws.write(0, 0, 123456789012345) # 15位整数
ws.write(0, 1, 1234567890123456) # 16位整数→可能显示为科学计数法
# 陷阱2:长整数可能失去精度
from decimal import Decimal
ws.write(1, 0, 9999999999999999) # 16个9,Excel可能显示为1E+16
2. 格式字符串的误区
# 错误的格式设置
style = xlwt.easyxf('num_format: #,##0') # 超过11位会显示为科学计数法
ws.write(2, 0, 12345678901, style) # 显示为1.23457E+10
3. 文本与数字的混淆
# 如果整数以文本形式存储,排序和计算会出问题
style_text = xlwt.easyxf('format: @') # 文本格式
ws.write(3, 0, '00123', style_text) # 文本"00123",无法参与数值计算
def write_integer_correctly(ws, row, col, value, format_type='auto'):
"""安全写入整数到Excel"""
if format_type == 'auto':
# 自动选择格式
if abs(value) < 1e11: # 小于11位
style = xlwt.easyxf('num_format: #,##0')
else: # 大整数,作为文本处理
style = xlwt.easyxf('format: @')
value = str(value)
elif format_type == 'text':
style = xlwt.easyxf('format: @')
value = str(value)
elif format_type == 'currency':
style = xlwt.easyxf('num_format: ¥#,##0')
elif format_type == 'no_comma':
style = xlwt.easyxf('num_format: 0')
else:
style = xlwt.easyxf('num_format: #,##0')
ws.write(row, col, value, style)
return style
2. 处理超大整数和ID类数据
def write_large_integer(ws, row, col, value):
"""处理超过15位的整数(如身份证号、信用卡号)"""
# 方法1:作为文本存储(推荐)
style = xlwt.easyxf('format: @')
ws.write(row, col, str(value), style)
# 方法2:添加前导撇号
# ws.write(row, col, "'" + str(value))
3. 创建可重用的格式样式
class IntegerFormats:
def __init__(self):
self.styles = {
'int_standard': xlwt.easyxf('num_format: #,##0'),
'int_no_comma': xlwt.easyxf('num_format: 0'),
'int_text': xlwt.easyxf('format: @'),
'int_currency': xlwt.easyxf('num_format: ¥#,##0'),
'int_percent': xlwt.easyxf('num_format: 0%'),
'int_leading_zeros': xlwt.easyxf('num_format: 00000'),
}
def get_style(self, name):
return self.styles.get(name, self.styles['int_standard'])
4. 完整的示例代码
import xlwt
def create_integer_workbook(data_list, filename='integers.xls'):
"""创建包含各种整数格式的工作簿"""
wb = xlwt.Workbook()
ws = wb.add_sheet('Integer Data')
# 设置列宽
ws.col(0).width = 256 * 15 # 256为单位
# 标题行
header_style = xlwt.easyxf(
'font: bold on; align: horiz center;'
)
headers = ['原始值', '标准格式', '文本格式', '货币格式', '自定义格式']
for col, header in enumerate(headers):
ws.write(0, col, header, header_style)
# 数据格式
formats = IntegerFormats()
for row, value in enumerate(data_list, start=1):
# 原始值(文本格式,保持原样)
ws.write(row, 0, str(value), formats.get_style('int_text'))
# 标准格式
try:
if isinstance(value, str):
num_value = int(value)
else:
num_value = int(value)
# 根据数值大小选择格式
if abs(num_value) < 1e11:
ws.write(row, 1, num_value, formats.get_style('int_standard'))
else:
ws.write(row, 1, str(num_value), formats.get_style('int_text'))
except:
ws.write(row, 1, 'N/A')
# 文本格式
ws.write(row, 2, str(value), formats.get_style('int_text'))
# 货币格式
try:
ws.write(row, 3, int(value), formats.get_style('int_currency'))
except:
ws.write(row, 3, 'N/A')
# 自定义格式(如固定位数)
if len(str(value)) == 6:
custom_style = xlwt.easyxf('num_format: "ID-"000000')
ws.write(row, 4, int(value), custom_style)
# 保存文件
wb.save(filename)
print(f"文件已保存: {filename}")
# 测试数据
test_data = [
123,
123456,
1234567890,
123456789012, # 12位
123456789012345, # 15位
1234567890123456, # 16位
'001234', # 带前导零
'12345678901234567890', # 20位
]
create_integer_workbook(test_data)
# 避免频繁创建样式对象
def efficient_writing():
wb = xlwt.Workbook()
ws = wb.add_sheet('Data')
# 预先创建样式
int_style = xlwt.easyxf('num_format: 0')
text_style = xlwt.easyxf('format: @')
for i in range(10000):
if i % 1000 == 0:
ws.write(i, 0, i, text_style) # ID类数据
else:
ws.write(i, 0, i, int_style) # 普通数值
3. 验证函数
def validate_excel_integer(value, max_digits=15):
"""验证整数是否适合Excel数值格式"""
if not isinstance(value, (int, str)):
return False, "必须是整数或数字字符串"
str_val = str(value).lstrip('-')
if not str_val.isdigit():
return False, "包含非数字字符"
if len(str_val) > max_digits:
return (False,
f"超过{max_digits}位,建议存储为文本。"
f"Excel会将{str_val[:max_digits]}之后显示为0")
return True, "适合存储为数值"
#,##0 格式
ID/编码类:作为文本存储,使用 @ 格式或添加前导撇号
超大整数(>15位):必须作为文本存储
前导零需要保留:使用文本格式或自定义格式如 00000
性能优化:预先创建样式对象,避免循环内创建
数据验证:写入前检查数值范围和格式要求
通过遵循这些最佳实践,可以避免xlwt处理整数时的常见陷阱,确保数据在Excel中正确显示和处理。