2011-12-11 34 views
2

我想用嵌入圖創建Excel電子表格。理想情況下,我想在Mac上使用Python。如果我不能這樣做,我想在Mac上使用某種Excel自動化來完成。如果我不能這樣做,我願意在Windows上通過COM來操作Excel,但我仍然希望從Python中完成。有沒有人有任何代碼?謝謝。如何使用嵌入圖生成Excel電子表格?

回答

4

下面是Windows上的Python COM的一個基本的例子:

import win32com.client 
from win32com.client import constants as c 

xl = win32com.client.gencache.EnsureDispatch('Excel.Application') 
xl.Visible = True 
wb = xl.Workbooks.Add() 
ws = xl.ActiveSheet 
ws.Range('A1').FormulaR1C1 = 'X' 
ws.Range('B1').FormulaR1C1 = 'Y' 
ws.Range('A2').FormulaR1C1 = 1 
ws.Range('A3').FormulaR1C1 = 2 
ws.Range('A4').FormulaR1C1 = 3 
ws.Range('B2').FormulaR1C1 = 4 
ws.Range('B3').FormulaR1C1 = 5 
ws.Range('B4').FormulaR1C1 = 6 
ws.Range('A1:B4').Select() 
ch = ws.Shapes.AddChart().Select() 
xl.ActiveChart.ChartType = c.xlXYScatterLines 
xl.ActiveChart.SetSourceData(Source=ws.Range("A1:B4")) 

它被記錄在Excel宏翻譯。這是宏,所以你可以看到它有多相似。只是記錄你想在Excel中做什麼,它翻譯成Python語法:

Sub Macro1() 
' 
' Macro1 Macro 
' 

' 
    ActiveCell.FormulaR1C1 = "X" 
    Range("B1").Select 
    ActiveCell.FormulaR1C1 = "Y" 
    Range("A2").Select 
    ActiveCell.FormulaR1C1 = "1" 
    Range("A3").Select 
    ActiveCell.FormulaR1C1 = "2" 
    Range("A4").Select 
    ActiveCell.FormulaR1C1 = "3" 
    Range("B2").Select 
    ActiveCell.FormulaR1C1 = "4" 
    Range("B3").Select 
    ActiveCell.FormulaR1C1 = "5" 
    Range("B4").Select 
    ActiveCell.FormulaR1C1 = "6" 
    Range("A1:B4").Select 
    ActiveSheet.Shapes.AddChart.Select 
    ActiveChart.ChartType = xlXYScatterLines 
    ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$B$4") 
End Sub 
+0

太棒了!有沒有一種簡單的方法來嵌入我用matplotlib生成的圖形? – vy32

0

我知道在Mac上處理Excel的主要工具是xlrd/xlwt和Excel 2004 XML格式。 AFAICT,這些都不支持嵌入式圖形。

所以,我認爲只留下通過Windows在Windows上操作Excel的選項。

+2

另一槍[R赫廷傑在Excel電子標籤....在家庭一些嚴重的IT技能:) – brettdj

+0

@Raymond,據我所知[openpyxl ](https://bitbucket.org/ericgazoni/openpyxl/)支持OSX ... [這裏](https://bitbucket.org/ericgazoni/openpyxl/issue/7/writing-a-file-from-osx-使用-n-instead-of)是在OSX下針對[openpyxl](https://bitbucket.org/ericgazoni/openpyxl/)提交的錯誤。它提供*一些*圖形支持,但它不是非常豐富 –