openpyxl 操作excel文档


1.打开已存在文档

import openyxl

wb = openpyxl.load_workbook(file_path)
ws = wb[sheet_name]

 

2.修改单元格数据

ws.cell(1,1).value = "test"

 

3.设置单元格样式(边框和字体)

from openpyxl.styles import Border, Side, Font, Alignment

border = Border(left=Side(style='medium',color='FF000000'),right=Side(style='medium',color='FF000000'))
font = Font(name='新宋体',size=10,bold=False,italic=False,vertAlign=None,underline='none',strike=False,color='FF000000')

ws.cell(1,1).border = border
ws.cell(1,1).font = font
# 自动换行
ws.cell(1,1).alignment = Alignment(wrapText=True)

 

4.将dataframe数据插入excel表中

from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd

df = pd.DataFrame([[1,2,3],[1,2,3]],columns=['a','b'])
for row in dataframe_to_rows(df, index=False, header=False):
    ws.append(row)

 

5.在excel中插入曲线图

from openpyxl.chart import (
    LineChart,
    Reference,
)
from openpyxl.chart.axis import DateAxis

line_chart = LineChart()
line_chart.title = "char_title"
line_chart.style = 13
# x y轴的名称
line_chart.y_axis.title = 'Y label'
line_chart.x_axis.title = 'X label'
# 图表所依据的数据位置
data = Reference(ws, min_col=2, min_row=1, max_col=2, max_row=10)
line_chart.add_data(data, titles_from_data=True)
# x轴坐标标签所依据的数据位置
x_labels = Reference(ws, min_col=1, min_row=2, max_row=10)
line_chart.set_categories(x_labels)
line_chart.width = 19
line_chart.height = 7
# 设置线条样式
line1 = line_chart.series[0]
line1.smooth = True # 线条光滑
line1.marker.symbol = "triangle"
line1.graphicalProperties.line.width = 20000 #线条粗细
# 插入图表的左上角位置
ws.add_chart(line_chart, "G2")

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM