將數(shù)據(jù)導(dǎo)出excel的通用代碼
在實(shí)際的項(xiàng)目開發(fā)中,一些重要數(shù)據(jù)需要保存到excel文件中,或者需要提供下載的功能,都會(huì)用到將數(shù)據(jù)導(dǎo)出excel的代碼。
本文介紹了將數(shù)據(jù)導(dǎo)出excel的通用python代碼,對(duì)創(chuàng)建excel文件、寫數(shù)據(jù)等過程進(jìn)行了封裝,開箱即用,且可復(fù)用。文章來源:http://www.zghlxwxcb.cn/news/detail-783864.html
import string
import xlsxwriter
from faker import Faker
def export_to_excel(filename, col_items, datas):
"""將信息導(dǎo)出為excel文件
Args:
filename (str): 文件名
col_items (list): 列名
datas (list): 數(shù)據(jù)信息
"""
# 生成.xlsx文件
workbook = xlsxwriter.Workbook(f'{filename}.xlsx')
# 設(shè)置sheet頁簽名稱
table = workbook.add_worksheet(filename)
# 表頭居中,背景灰色,字體顏色為白色
header_format = workbook.add_format({'align': 'center',
'bg_color': 'gray',
"color": "white",
"font": "宋體",
"bold": True,
"border": 1})
# 數(shù)據(jù)樣式:居中,帶邊框,字體
data_format = workbook.add_format({'align': 'center', "border": 1})
data_format.set_font("Calibri Light")
# 26個(gè)英文字母,大寫
chars = string.ascii_uppercase
# 設(shè)置列名及寬度
for idx, col in enumerate(col_items):
# 列名,寬度
col_name, col_width = col
col_code = chars[idx]
# 寫入列名
table.write(0, idx, col_name, header_format)
table.set_column(f'{col_code}:{col_code}', col_width)
# 列數(shù)
col_num = len(col_items)
# 循環(huán)寫入數(shù)據(jù)
for index, item in enumerate(datas):
# 一行為一條數(shù)據(jù)
row = index + 1
for i in range(col_num):
table.write(row, i, item[i], data_format)
# 關(guān)閉
workbook.close()
if __name__ == "__main__":
# 構(gòu)造數(shù)據(jù)
faker_obj = Faker(locale='zh')
# 文件名
filename ='人員名單'
# 列名
cols = [('序號(hào)', 10), ('姓名', 20)]
# 構(gòu)造數(shù)據(jù)
datas= []
for i in range(10):
datas.append((i + 1, faker_obj.name()))
# 將數(shù)據(jù)信息導(dǎo)出到excel文件中
export_to_excel(filename, cols, datas)
測(cè)試上述代碼,生成的excel文件如下圖所示:文章來源地址http://www.zghlxwxcb.cn/news/detail-783864.html
到了這里,關(guān)于數(shù)據(jù)導(dǎo)出excel的通用python代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!