python导出excel表格
Python可以使用pandas模块导出excel
import pandas as pd
class Export:
@classmethod
def export_excel(cls, export_list):
table_name = "域名信息.xlsx"
with pd.ExcelWriter(table_name) as writer:
pf_failed = cls.format_excel(export_list)
pf_failed.to_excel(writer, sheet_name="Sheet1", index=False)
writer.save() # 保存表格
@classmethod
def format_excel(cls, export_data: list):
columns_map = {
"domain_name": "域名",
"product_name": "产品",
"apply_name": "申请人",
"apply_time": "申请时间",
"itsm_id": "itsm_id",
"apply_reason": "备注",
"tech_name": "开发负责人",
"ops_name": "运维负责人",
} # 将列名替换为中文
order = [
"domain_name",
"product_name",
"apply_name",
"apply_time",
"itsm_id",
"apply_reason",
"tech_name",
"ops_name",
] # 指定字段顺序
pf = pd.DataFrame(list(export_data)) # 将字典列表转换为DataFrame
pf = pf[order]
pf.rename(columns=columns_map, inplace=True)
pf.fillna(" ", inplace=True) # 替换空单元格
return pf
if __name__ == "__main__":
record_list = [
{
"domain_name": "www.baidu.com",
"product_name": "百度",
"apply_name": "李彦宏",
"apply_time": "2022-04-30",
"itsm_id": "ID1001",
"apply_reason": "测试1",
"tech_name": "李彦宏",
"ops_name": "李彦宏"
},
{
"domain_name": "www.qq.com",
"product_name": "腾讯",
"apply_name": "马化腾",
"apply_time": "2022-04-30",
"itsm_id": "ID1002",
"apply_reason": "测试1",
"tech_name": "马化腾",
"ops_name": "马化腾"
}
]
Export.export_excel(record_list)
效果: