xlwt工具使用,生成excel栏位宽度可自适应内容长度
import xlwt
result = [
['姓名', '性别', '年龄'],
['张三11111111111111111', '男', 186],
['李四', '男', 18],
['小花', '女', 16],
['梅梅', '女', 14],
]
total = [
['男(人)', '女(人)', '共(人)'],
[2, 2, 4],
]
# 获取字符串长度,一个中文的长度为2
def len_byte(value):
length = len(value)
utf8_length = len(value.encode('utf-8'))
length = (utf8_length - length) / 2 + length
return int(length)
#设置字体
font = xlwt.Font()
font.bold = True
#设置边框
borders = xlwt.Borders()
borders.left = xlwt.Borders.THIN
borders.right = xlwt.Borders.THIN
borders.top = xlwt.Borders.THIN
borders.bottom = xlwt.Borders.THIN
#设置居中
alignment = xlwt.Alignment()
alignment.horz = xlwt.Alignment.HORZ_CENTER #水平方向
alignment.vert = xlwt.Alignment.VERT_TOP #垂直方向
#设置背景颜色
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 3 #背景颜色
#定义不同的excel style
style1 = xlwt.XFStyle()
style1.font = font
style1.borders = borders
style1.alignment = alignment
style2 = xlwt.XFStyle()
style2.borders = borders
style2.alignment = alignment
style3 = xlwt.XFStyle()
style3.borders = borders
style3.alignment = alignment
style4 = xlwt.XFStyle()
style4.borders = borders
style4.font = font
style4.pattern = pattern
style4.alignment = alignment
workbook = xlwt.Workbook(encoding='utf-8')
worksheet = workbook.add_sheet('My Worksheet')
#确定栏位宽度
col_width = []
for i in range(len(result)):
for j in range(len(result[i])):
if i == 0:
col_width.append(len_byte(result[i][j]))
else:
if col_width[j] < len_byte(str(result[i][j])):
col_width[j] = len_byte(result[i][j])
#设置栏位宽度,栏位宽度小于10时候采用默认宽度
for i in range(len(col_width)):
if col_width[i] > 10:
worksheet.col(i).width = 256 * (col_width[i] + 1)
#设置栏位高度
# tall_style = xlwt.easyxf('font:height 720;') #设置字体高度
# row0 = worksheet.row(0)
# row0.set_style(tall_style)
#excel内容写入
for i in range(len(result)):
for j in range(len(result[i])):
if i == 0:
worksheet.write(i, j, label=result[i][j], style=style1)
else:
worksheet.write(i, j, label=result[i][j], style=style2)
#excel统计结果写入
for m in range(len(total)):
for n in range(len(total[m])):
if m == 0:
worksheet.write(m + i + 3, n + 2, label=total[m][n], style=style4)
else:
worksheet.write(m + i + 3, n + 2, label=total[m][n], style=style2)
#合并单元格
worksheet.write_merge(m + i + 4, m + i + 6, 2, 4, label='统计: 签名:', style=style3)
workbook.save('Excel_Workbook.xls')
xlwt模块自适应列宽写入excel
最近需要写一个用python将数据写入excel的小工具,遇到了自适应列宽写入excel的问题,特此记录下解决思路及过程。
运行环境:Windows10、PyCharm 2017.3.2、Python3.6、xlwt1.3.0
编写小dome如下
import xlwt
'''
利用python的xlwt模块自适应列宽写入excel
'''
row_num = 0 # 记录写入行数
# 个人信息:姓名,性别,年龄,手机号,固定电话,邮箱
line_name = ['姓名','性别','年龄','手机号','固定电话','邮箱']
data = [
['厘清','女','31','18745214693','010-4784125','5412546qq.com'],
['张三','男','26','18245554693','010-4784125','无'],
['王武','男','19','13245266693','无','785992546qq.com'],
['熊大','男','16','无','010-4784125','115412546qq.com'],
['熊二','男','22','18745214693','010-4784125','3654126qq.com']
]
# 创建一个Workbook对象
book = xlwt.Workbook(encoding="utf-8",style_compression=0)
# 创建一个sheet对象
sheet = book.add_sheet('person_msg', cell_overwrite_ok=True)
# 写入列名
for name in range(0, len(line_name)):
sheet.write(row_num, name, line_name[name])
row_num += 1
# 写入数据
for i in range(0, len(data)):
for j in range(0, len(data[i])):
sheet.write(row_num, j, data[i][j])
row_num += 1
# 保存excel文件
book.save('person_msg.xls')
生成的excel文件没有任何排版比较乱
解决思路
获取每列写入字符长度,比较出每列最宽的长度,最后设置合适的长度。
计算字符串的长度时要注意一个汉字占两个字节,需要指定字符串的字符集才能获取正确的字符数
>>> str = 'liming李明'
>>> len(str)
8
>>> len(str.encode('gb18030'))
10
最后代码如下
import xlwt
import copy
'''
利用python的xlwt模块自适应列宽写入excel
'''
# 获取每列所占用的最大列宽
def get_max_col(max_list):
line_list = []
# i表示行,j代表列
for j in range(len(max_list[0])):
line_num = []
for i in range(len(max_list)):
line_num.append(max_list[i][j]) # 将每列的宽度存入line_num
line_list.append(max(line_num)) # 将每列最大宽度存入line_list
return line_list
def write_excel():
row_num = 0 # 记录写入行数
col_list = [] # 记录每行宽度
# 个人信息:姓名,性别,年龄,手机号,固定电话,邮箱
data = [
['姓名','性别','年龄','手机号','固定电话','邮箱'],
['厘清','女','31','18745214693','0104784125','5412546qq.com'],
['张三','男','26','18245554693','010-4784125','无'],
['王武','男','19','13245266693','无','785992546qq.com'],
['熊大','男','16','无','010-4784125','115412546qq.com'],
['熊二','男','22','18745214693','010-4784125','3654126qq.com']
]
# 创建一个Workbook对象
book = xlwt.Workbook(encoding="utf-8",style_compression=0)
# 创建一个sheet对象
sheet = book.add_sheet('person_msg', cell_overwrite_ok=True)
col_num = [0 for x in range(0, len(data))]
# 写入数据
for i in range(0, len(data)):
for j in range(0, len(data[i])):
sheet.write(row_num, j, data[i][j])
col_num[j] = len(data[i][j].encode('gb18030')) # 计算每列值的大小
col_list.append(copy.copy(col_num)) # 记录一行每列写入的长度
row_num += 1
# 获取每列最大宽度
col_max_num = get_max_col(col_list)
# 设置自适应列宽
for i in range(0, len(col_max_num)):
# 256*字符数得到excel列宽,为了不显得特别紧凑添加两个字符宽度
sheet.col(i).width = 256 * (col_max_num[i] + 2)
# 保存excel文件
book.save('person_msg.xls')
write_excel()
生成excel文件person_msg.xls
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。