您正在寻找replace()
>>> x = '1,2,3'
>>> x.replace(',', '')
'123'
for row, nums in enumerate(d):
for col, value in enumerate(nums):
try:
value = int(value.replace(',', ''))
except:
pass
sh.write(col, row , value)
样式格式的例子:
style = xlwt.XFStyle()
font = xlwt.Font()
font.bold = True
style.font = font
sh.write(col, row , value, style=style)
总结一下:
style = xlwt.XFStyle()
font = xlwt.Font()
font.bold = True
style.font = font
for row, nums in enumerate(d):
for col, value in enumerate(nums):
try:
value = int(value.replace(',', ''))
except:
pass
if col == 0:
sh.write(col, row , value, style=style)
else:
sh.write(col, row , value)
另一种方法是使用easyxf()
:
head = xlwt.easyxf('align: horiz center; font: bold 1,')
common = xlwt.easyxf('align: horiz center;')
for row, nums in enumerate(d):
for col, value in enumerate(nums):
try:
value = int(value.replace(',', ''))
except:
pass
if col == 0:
sh.write(col, row, value, style=head)
else:
sh.write(col, row, value, style=common)
宽度&高地
添加一个bedore wb.save()
import itertools
col_width = 26 * 20
try:
for i in itertools.count():
sh.col(i).width = col_width
except ValueError:
pass
设置单元格格式
Additional formats
num = xlwt.easyxf('align: horiz center;', '#,##')
if col == 0:
sh.write(col, row, value, style=head)
else:
if type(value) is int:
sh.write(col, row, value, style=num)
else:
sh.write(col, row, value, style=common)
全部片段:
import itertools
import xlwt
wb = xlwt.Workbook()
sh = wb.add_sheet('S1')
d = [['Numbers', '4,849,377', '736,732', '6,731,484'],
['Letters', 'a', 'b', 'c'], ['Colors', 'red', 'green', 'yellow']]
head = xlwt.easyxf('align: horiz center; font: bold 1,')
common = xlwt.easyxf('align: horiz center;')
num = xlwt.easyxf('align: horiz center;', '#,##')
for row, nums in enumerate(d):
for col, value in enumerate(nums):
try:
value = int(value.replace(',', ''))
except:
pass
if col == 0:
sh.write(col, row, value, style=head)
else:
if type(value) is int:
sh.write(col, row, value, style=num)
else:
sh.write(col, row, value, style=common)
col_width = 200 * 20
try:
for i in itertools.count():
sh.col(i).width = col_width
except ValueError:
pass
wb.save('tryx.xls')
print 'Exported'
好。我得到第一行有粗体文本。但是,我不想取代逗号。我需要保持他们。而且,斜体,列宽以及数据居中的情况如何?正如我所说,它应该看起来像图像中的数据。 – user5403501
@ user5403501更新了对齐方式 –
@ user3990145:除了扩大列外,我得到了一切。我使用了代码的第二种方法;与easyxf的一个。你能告诉我如何扩大列到一定的宽度? – user5403501