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.top = 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()
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;')
file.row(0).set_style(tall_style) # 0表示第一行
設置列寬
file.col(0).width = 512 * 7 # 0表示第一行,256表示一個字符,512我試的差不多一個文字
把excel格式數據寫入內存中的例子寫法:
import xlwt from io import BytesIO def write_excel(data=[]): # print(data) # 操作內存的 stream = BytesIO() # 寫入excel格式數據 workbook = xlwt.Workbook(encoding='utf-8') file = workbook.add_sheet('出行記錄數據') # 標題 title = ["序號", "客人名稱", "手機號", "體溫", "餐廳名稱", "進入時間", "出去時間"] for col_index in range(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數據轉下格式 if isinstance(value, datetime.datetime): value = value.strftime('%Y-%m-%d %H:%M:%S') file.write(row_index, col_index, value) # 文件內容保存在內存中 workbook.save(stream) # 直接從內存中返回數據 return stream.getvalue() if __name__ == '__main__': value = write_excel() f = open(file="temp.xls", mode="wb") f.write(value) f.close()
# 使用場景: 當前端a標簽請求后端拿excel文件,后端及時生成excel,不寫入到硬盤時侯使用。