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