一、代碼
備注:封裝好了(可直接呼叫)
""" -*- coding:utf-8 -*- @Time :2020/8/20 21:02 @Author :Jarvis @File :jar_excel_util.py @Version:1.0 """ from typing import List import xlwt class JarExcelUtil: def __init__(self, header_list: List[list]): """ :param header_list: 如下格式 例1:默認列寬 header_list = [ ['序號'], # 表格第0列[此串列頭名稱] ['姓名'], ['性別'], ['愛好'], ['生日'] ] 例2:自定義列寬(列寬值為int型別 英文字符長度 如:10 表示列寬為10個英文字符長度) header = [ ['序號', 5], # 表格第0列[此串列頭名稱,列寬] ['姓名', 10], # 表格第1列[此串列頭名稱,列寬] ['性別', 10], ['愛好', 10], ['生日', 20] ] """ self.data = header_list def write(self, out_file, data_body: List[list], sheet_name='sheet'): """ 寫入資料 :param out_file: 保存檔案(如:test.xlsx) :param data_body: data_body[0]為表格第0行資料 data_body[0][0]為表格第0行第0列單元格值 :param sheet_name: """ # step1 判斷資料正確性(每行列數是否與表頭相同) count = 0 for pro in data_body: if len(pro) != len(self.data): raise Exception( 'data_body資料錯誤 第{}行(從0開始) 需為{}個元素 當前行{}個元素:{}'.format(count, len(self.data), len(pro), str(pro))) count += 1 # step2 寫入資料 wd = xlwt.Workbook() sheet = wd.add_sheet(sheet_name) # 表頭 for col in self.data: # 默認列寬 if len(col) == 1: sheet.write(0, self.data.index(col), str(col[0])) # 自定義列寬 if len(col) == 2: sheet.write(0, self.data.index(col), str(col[0])) # 設定列寬 sheet.col(self.data.index(col)).width = 256 * col[1] # 15個英文字符 # 表體 index = 1 for pro in data_body: for d in self.data: value = pro[self.data.index(d)] # 若值型別是int、float 直接寫入 反之 轉成字串寫入 if type(value) == int or type(value) == float: sheet.write(index, self.data.index(d), value) else: sheet.write(index, self.data.index(d), str(value)) index += 1 wd.save(out_file) if __name__ == '__main__': header = [ ['序號', 5], ['姓名', 10], ['性別', 10], ['愛好', 10], ['生日', 20] ] # header = [ # ['序號'], # ['姓名'], # ['性別'], # ['愛好'], # ['生日'] # ] body = [ [1, '張三', '男', '籃球', '1994-07-23'], [2, '李四', '女', '足球', '1994-04-03'], [3, '王五', '男', '兵乓球', '1994-09-13'] ] JarExcelUtil(header_list=header).write(out_file='測驗.xlsx', data_body=body)
二、效果
生成的Excel

三、常用操作
3.1、設定行高
# 行高(第0行) sheet.row(0).height_mismatch = True sheet.row(0).height = 20 * 20 # 20為基數 * 20榜
3.2、設定列寬
# 列寬(第0列) sheet.col(0).width = 256 * 30 # 256為基數 * 30個英文字符(約)
3.3、凍結(列與行)
# 凍結(列與行) sheet.set_panes_frozen('1') sheet.set_horz_split_pos(2) # 凍結前2行 sheet.set_vert_split_pos(3) # 凍結前3列 # 凍結首行 sheet.set_panes_frozen('1') sheet.set_horz_split_pos(1) # 凍結前1行(即首行)
3.4、設定單元格對齊方式
# 設定對齊方式 style_1 = xlwt.XFStyle() al_1 = xlwt.Alignment() al_1.horz = xlwt.Alignment.HORZ_CENTER # 水平居中 al_1.vert = xlwt.Alignment.VERT_CENTER # 垂直居中 style_1.alignment = al_1 sheet.write(0, 0, '第0行第0列單元格值', style_1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/106312.html
標籤:其他
