DataFrame to_excel with border lines

给pandas的DataFrame存到excel文件里并添加表格框线。

主要使用styleframe包。

details见代码。

# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 19:55:27 2019

@author: Fanxiaolei
"""
import pandas as pd
from styleframe import StyleFrame
data=[{"name":"Amay","age":20,"result":80},
      {"name":"Tom","age":32,"result":90}]

df=pd.DataFrame(data)
sf=StyleFrame(df)
ew=sf.ExcelWriter(r'C:UsersFanXiaoLeiDesktop1.xlsx')
sf.to_excel(ew)
ew.save()

 效果如图:

 数据写入已存在的工作簿里。pandas的DataFrame直接to_excel会引起原有的工作表都丢失。所以需要使用excelwriter进行处理。使用stylesrame包的时候一样要进行处理。

代码如下:

# -*- coding: utf-8 -*-
"""
Created on Sun Mar 17 19:55:27 2019

@author: Fanxiaolei
"""
import pandas as pd
from styleframe import StyleFrame
from openpyxl import load_workbook
data=[{"name":"Amay","age":20,"result":80},
      {"name":"Tom","age":32,"result":90}]

df=pd.DataFrame(data)
sf=StyleFrame(df)
excelpath=r'C:UsersFanXiaoLeiDesktop1.xlsx'
ew=sf.ExcelWriter(excelpath)
wb=load_workbook(excelpath)
ew.book=wb
ew.sheets=dict((ws.title,ws) for ws in wb._sheets)
sf.to_excel(ew,sheet_name='结果')
ew.save()

结果如下图所示:

 可以看到原有的工作表还存在。

原文地址:https://www.cnblogs.com/FanXiaoLei/p/14218395.html