Pandas与openpyxl库的 "完美" 融合!
前言
DataFrame转工作簿
import pandas as pd
data = {
"姓名": ["张三", "李四"],
"性别": ["男", "女"],
"年龄": [15, 25],
}
df = pd.DataFrame(data)
df
如果想要给表头设置为红色字体,并居中,应该如何设置呢?
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.styles import Font
from openpyxl.styles import Alignment
wb = Workbook()
ws = wb.active
for row in dataframe_to_rows(df, index=False, header=True):
ws.append(row)
font = Font(name="微软雅黑",size=10, bold=True,italic=False,color="FF0000")
alignment = Alignment(horizontal="center",vertical="center")
for i in range(1,df.shape[1]+1):
cell = ws.cell(row=1, column=i)
print(cell.value)
cell.font = font
cell.alignment = alignment
wb.save("pandas.xlsx")
工作簿转DataFrame
import pandas as pd
from openpyxl import load_workbook
wb = load_workbook(filename="df_to_openpyxl.xlsx")
ws = wb.active
values = ws.values
df = pd.DataFrame(values)
df
各位伙伴们好,詹帅本帅搭建了一个个人博客和小程序,汇集各种干货和资源,也方便大家阅读,感兴趣的小伙伴请移步小程序体验一下哦!(欢迎提建议)
推荐阅读
推荐阅读
评论