python实现生成多种文件格式:excel、csv、pdf
bash
import data_util, time_util
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
if __name__ == '__main__':
data = data_util.get_superset_data()
df = ''
if (len(data) > 0):
# 应用函数转换时间戳
for entry in data:
entry['日程开始时间'] = time_util.convert_to_pst(entry['日程开始时间'])
entry['日程结束时间'] = time_util.convert_to_pst(entry['日程结束时间'])
if isinstance(data, dict):
if data:
df = pd.DataFrame.from_records([data])
else:
print("Data is an empty dictionary")
df = pd.DataFrame()
elif isinstance(data, list):
dfs = [pd.DataFrame.from_records([item]) for item in data if isinstance(item, dict)]
df = pd.concat(dfs, ignore_index=True)
else:
print("Data is not a list or a dictionary")
df = pd.DataFrame()
# df.to_excel('media.xlsx', index=False)
# df.to_csv('media.csv', index=False)
# PDF文件格式
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
#print(df)
# 创建一个PDF文件
with PdfPages('media.pdf') as pdf:
# 将DataFrame绘制成表格
fig, ax = plt.subplots(figsize=(8.27, 11.69), dpi=400) # 设置dpi为300,提高图像质量
ax.axis('tight')
ax.axis('off')
ax.table(cellText=df.values, colLabels=df.columns, loc='top', cellLoc='center')
pdf.savefig(dpi=400) # 将当前图形保存到PDF,并设置dpi
plt.close()
print("PDF文件已生成")