pythonxlwt写⼊excel_python写⼊excel数据xlwt模块xlwt模块介绍
把内容写⼊excel表的模块
xlwt模块的使⽤
创建excel⽂件
#导⼊模块
import xlwt
# 创建⼀个workbook 设置编码
workbook = xlwt.Workbook(encoding='utf-8')
# 创建⼀个worksheet
file = workbook.add_sheet('POS运营简报')
保存写⼊的excel数据
# 保存excel⽂件
workbook.save(excel_filepath)
写⼊
⼀个单元格写⼊
file.write(row, column,content)
# 注: row和colum从0开始
例⼦:
file.write(1,1,'zezhou')
合并单元格写⼊
file.write_merge(row1,row2,column1,column2,content)
例⼦:
file.write_merge(1,3,0,1,'zezhou')
设置样式
加边框
style = XFStyle()
# 边框
borders = Borders()
borders.left = 1
borders.right = 1

borders.bottom = 1
# 赋值
style.borders = borders
# 写⼊
file.write(1,1,'zezhou',style)
居中
style = XFStyle()
al = xlwt.Alignment()
al.horz = 0x02 # 设置⽔平居中
al.vert = 0x01 # 设置垂直居中
# 赋值
style.alignment = al
file.write(1,1,'zezhou',style)
字体样式
1.调整字体⼤⼩
# 创建⼀个⽂本格式,包括字体、字号和颜⾊样式特性fnt = Font()python怎么读取excel文件数据
fnt.height = 20 * 20 # 第⼀个20默认,第⼆个字号# 赋值
style.font = fnt
file.write(1,1,'zezhou',style)
2.加粗字体
fnt.blod = True
⾃动换⾏
# 默认⽤xlwt写⼊的内容是不会换⾏的
# 设置后内容超出⾃动换⾏或者是遇到\n⾃动换⾏
style.alignment.wrap = 1 # ⾃动换⾏
设置⾏⾼
tall_style = xlwt.easyxf('font:height 700;')
设置列宽
把excel格式数据写⼊内存中的例⼦写法:
importxlwtfrom io importBytesIOdef write_excel(data=[]):#print(data)
#操作内存的
stream =BytesIO()#写⼊excel格式数据
workbook = xlwt.Workbook(encoding='utf-8')
file= workbook.add_sheet('出⾏记录数据')#标题
title = ["序号", "客⼈名称", "⼿机号", "体温", "餐厅名称", "进⼊时间", "出去时间"]for col_index inrange(0, len(title)): file.write(0, col_index, title[col_index])#主体数据
for row_index in range(1, len(data)+1):
temp= data[row_index-1]
file.write(row_index, 0, row_index)for col_index in range(1, len(temp)+1):
value= temp[col_index - 1]#datime数据转下格式
ifisinstance(value, datetime.datetime):
value= value.strftime('%Y-%m-%d %H:%M:%S')
file.write(row_index, col_index, value)#⽂件内容保存在内存中
workbook.save(stream)#直接从内存中返回数据
value=write_excel()
f= open(file="temp.xls", mode="wb")
f.write(value)
f.close()
# 使⽤场景: 当前端a标签请求后端拿excel⽂件,后端及时⽣成excel,不写⼊到硬盘时侯使⽤。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。