如何使用Python在Excel 2003的工作表中嵌入绘图
我有下面的函数做我希望它做的事情,只是我不想在新的工作表上生成图表,而是想把它嵌入到写数据的工作表中。另外,如何删除图例?以下是我得到的:如何使用Python在Excel 2003的工作表中嵌入绘图,python,excel,excel-2003,vba,Python,Excel,Excel 2003,Vba,我有下面的函数做我希望它做的事情,只是我不想在新的工作表上生成图表,而是想把它嵌入到写数据的工作表中。另外,如何删除图例?以下是我得到的: def Get_IV_Data(current_file): xlApp = win32com.client.Dispatch('Excel.Application') xlApp.Visible = True xlBook = xlApp.Workbooks.Add() xlSheet = xlBook.Sheets(
def Get_IV_Data(current_file):
xlApp = win32com.client.Dispatch('Excel.Application')
xlApp.Visible = True
xlBook = xlApp.Workbooks.Add()
xlSheet = xlBook.Sheets(1)
xlSheet.Name = filename
for i in range(0, 10):
fluff = current_file.readline()
Input_Parameters = fluff.split("\t")
from operator import itemgetter
Cal_Std_V = float(itemgetter(2)(Input_Parameters))
xlSheet.Cells(1,1).Value = "V"
xlSheet.Cells(1,2).Value = "I"
xlSheet.Cells(1,3).Value = "P"
output_line = 2
# Assign the data to lists
for line in current_file:
try:
a = line.split("\t")
STD1, STD2, STD3, V, I, Vcorr, Icorr, v1, v2, v3 = a
I = round(float(I) * (Cal_Std_V / float(STD1)), 6)
P = round(float(V) * I, 3)
xlSheet.Cells(output_line, 1).Value = V
xlSheet.Cells(output_line, 2).Value = I
xlSheet.Cells(output_line, 3).Value = P
output_line += 1
except ValueError:
pass
chart = xlApp.Charts.Add()
chart.Name= "Plot "+xlSheet.Name
series = chart.SeriesCollection(1)
series.XValues= xlSheet.Range("A2:A200")
series.Values= xlSheet.Range("B2:B200")
series.Name= filename
通过调用图表的location方法设置图表的位置,该方法包含两个参数
第一个名为Where,它接受一个名为xlLocationAsNewSheet、xlLocationAsObject和xlLocationAutomatic的枚举,其值分别为1、2和3
第二个参数是Name,它是工作表名称
下面是Python中的示例:
xlLocation = {"AsNewSheet": 1,
"AsObject": 2,
"Automatic": 3 }
chart.Location(xlLocation["AsObject"], xlSheet.Name)
如果你喜欢魔术数字,你可以改成
chart.Location(2, xlSheet.Name)
在excel中记录一个宏,该宏的功能完全符合您的要求。然后,使用生成的代码作为如何使用COM对象的指南。@Steven Rumbalski,有没有办法将宏代码翻译成python,或者我必须通过反复试验来解决这个问题?这给了我一个错误。我认为AddChart是MS Excel 2007的新功能,在2003年不起作用?你是对的。这是针对Excel2007的。现在我有时间讨论更多内容,我已经完全修改了我的答案。嗯,这看起来很有希望,但它声称shapes对象没有属性AddChart。我开始认为这在MS 2003中不可能实现。@Ben:我不再使用上面答案中的shapes对象。按照chart=xlApp.Charts.Add的方式继续创建图表,但在创建图表后,请调用chart.Location方法来设置位置。这样就可以了。谢谢你救了我的命。