from openpyxl import load_workbook, workbook
from openpyxl.chart import Series, Reference, ScatterChart
LineColor = ["0000ff", "FF00FF", "00ff00", "ff9900", "ff0000", "00ffff", "7f6000", "ffe599", "4a86e8", "ea9999",
"050505", "808080", "c02080", "201119", "68ff23"]
# 蓝色 紫色 绿色 棕色 红色 草色 褐色 淡黄色 浅绿色 浅红色
MarkStyle = ['dash', 'dot', 'diamond', 'circle', 'plus', 'square', 'auto', 'picture', 'star', 'x', 'triangle']
DashStyle = ['sysDash', 'lgDash', 'sysDashDotDot', 'sysDashDot', 'sysDot', 'dot', 'lgDashDot', 'lgDashDotDot',
'dashDot', 'solid', 'dash']
def myChart(ws, xrow, xcol, srow, scol, nrow, ncol): # 2 1 14 4
"""
:param xnrow: x_axis first cell row 横坐标一列第一个数字的单元格行号,一般是标题A1,1
:param xcol: x_axis first cell col 横坐标一列第一个数字的单元格列号,一般是标题A1,1
:param srow: data start row 数据区域第一行包括标题,一般是B1,所以是1
:param scol: data start col 数据区域第一行包括标题,一般是B1,所以是2
:param ncol: the total number of data column 数据区域的列数,一般是线条的个数
:param nrow: range row number 整体的行号,包括标题
:return: the chart handle
:描述:
"""
chart = ScatterChart()
chart.title = "增益和噪声系数"
chart.style = 35
chart.y_axis.title = '增益 / db'
chart.x_axis.title = '频率 / Ghz'
chart.width = 16
chart.height = 12
chart.x_axis.majorUnit =0.3
chart.x_axis.scaling.min = float(ws.cell(xrow+1, xcol).value)-chart.x_axis.majorUnit # 横坐标第一个数
chart.x_axis.scaling.max = float(ws.cell(xrow + nrow - 2, xcol).value)+chart.x_axis.majorUnit # 横坐标最后一个数
chart.legend.position = "tr" # t,r,tr,l,b
xdata = Reference(ws, min_row=xrow+1, min_col=xcol, max_row=xrow + nrow - 2)
for i in range(ncol): # 0 ,1,2
ydata = Reference(ws, min_row=srow, min_col=i + scol, max_row=nrow + srow - 1)
s = Series(ydata, xvalues=xdata, title_from_data=True)
chart.append(s)
s1 = chart.series[i]
s1.marker.symbol = MarkStyle[2]
s1.marker.graphicalProperties.solidFill = "505050"
s1.marker.graphicalProperties.line.solidFill = "050505"
s1.marker.graphicalProperties.line.width = 35000
s1.graphicalProperties.line.dashStyle = DashStyle[9]
s1.graphicalProperties.line.solidFill = LineColor[i]
s1.graphicalProperties.line.width = 30000 # 设置线宽
s1.graphicalProperties.line.noFill = False
return chart
if __name__=="__main__":
wb = load_workbook(r"material\excel_chart_line.xlsx", data_only=False)
ws = wb['Sheet1']
# 添加
ws.add_chart(myChart(ws, 1, 1, 1, 3, 15, 8), "M2")
# 保存文件
wb.save(r"material\excel_chart_line.xlsx")