使用Python将Excel中的图表导出为图片

5

我一直在尝试使用Python将Excel中的图表导出为图像文件(JPG或ING)。我正在查看WIn32com。以下是目前的代码。

import win32com.client as win32
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = excel.Workbooks.Open("<WORKSHEET NAME>")
r = wb.Sheets("<SHEET NAME>").Range("A1:J50") 
# Here A1:J50 is the area over which cart is
r.CopyPicture()

我遇到了困难。现在我需要将所选范围复制到文件中。任何帮助或指向文档的提示都可以对我有很大帮助。

上述代码是基于以下VBA脚本模拟的:

Sub Export_Range_Images()
    ' =========================================
    ' Code to save selected Excel Range as Image
    ' =========================================
    Dim oRange As Range
    Dim oCht As Chart
    Dim oImg As Picture

    Set oRange = Range("A1:B2")
    Set oCht = Charts.Add
    oRange.CopyPicture xlScreen, xlPicture
    oCht.Paste
    oCht.Export FileName:="C:\temp\SavedRange.jpg", Filtername:="JPG"
End Sub

代码片段来自:http://vbadud.blogspot.com/2010/06/how-to-save-excel-range-as-image-using.html


1
我的建议是与Excel划清界限。为什么要在Excel中制作图表,然后再使用Python呢?只需使用Python读取数据,并使用matplotlib进行绘图即可。 - TJD
不幸的是,之前的工作让我不得不坚持使用Excel。而且有超过10个图表是从多个工作表中绘制的。 - Parikshit
为什么不直接导出图表呢?Sheet对象有一个ChartObjects集合:每个ChartObject都有一个包含Export方法的Chart。复制包含图表的范围,然后将其粘贴到空图表中似乎是绕了一个大弯路。 - Tim Williams
4个回答

7
对我来说,这个方法很有效:

from win32com.client import Dispatch

app = Dispatch("Excel.Application")
workbook_file_name = 'Programmes.xlsx'
workbook = app.Workbooks.Open(Filename=workbook_file_name)

# WARNING: The following line will cause the script to discard any unsaved changes in your workbook
app.DisplayAlerts = False

i = 1
for sheet in workbook.Worksheets:
    for chartObject in sheet.ChartObjects():
        # print(sheet.Name + ':' + chartObject.Name)
        chartObject.Chart.Export("chart" + str(i) + ".png")
        i += 1

workbook.Close(SaveChanges=False, Filename=workbook_file_name)

或者这样:
from win32com.client import Dispatch

app = Dispatch("Excel.Application")
workbook_file_name = 'Programmes.xlsx'
workbook = app.Workbooks.Open(Filename=workbook_file_name)
app.DisplayAlerts = False
try:
    workbook.SaveAs(Filename="ExcelCharts.htm", FileFormat=44)  # 44 = html file format
except Exception as ex:
    print(ex)
finally:
    workbook.Close(SaveChanges=False, Filename=workbook_file_name)

1
有没有一种方法可以导出到特定路径? - Shreamy
我无法更改输出路径,有没有办法更改? - Sanch

6

我不得不查看一些VBA示例才能使其正常工作。虽然我不喜欢回答自己的问题,但我将这里留下来供可能需要的人使用。

    import win32com.client as win32
    wb = excel.Workbooks.Open(excel_file)
    selection = "A1:J30" 
    xl_range = wb.Sheets(<sheet_name>).Range(selection)
    excel.ActiveWorkbook.Sheets.Add(                  After=excel.ActiveWorkbook.Sheets(3)).Name="image_sheet"
    cht = excel.ActiveSheet.ChartObjects().Add(0,0,
                                            xl_range.Width, xl_range.Height)
    xl_range.CopyPicture()
    # add the chart to new sheet
    cht.Chart.Paste()
    # Export the sheet with the chart to a new file
    cht.Chart.Export(<image_filename>)
    # Delete the sheet
    cht.Delete()
    excel.ActiveSheet.Delete()
    # Close the book
    excel.ActiveWorkbook.Close()

6

我知道这是一个老问题,但它帮助我找到了正确的方向,所以我回来分享我的完成脚本,该脚本可以查找工作表中的所有图表并将其导出为.png文件。

上面的脚本可以工作,但由于它仅复制工作表中的一个范围,因此您需要确保图表位于该位置。

    import win32com.client as win32
    from win32com.client import Dispatch
    import os

    xlApp = Dispatch('Excel.Application')

    workbook = xlApp.Workbooks.Open("Book1.xls")
    xlApp.Sheets("Sheet1").Select()

    xlSheet1 = xlApp.Sheets(1)

    #WARNING: The following line will cause the script to discard any unsaved changes in your workbook
    #Ensure to save any work before running script
    xlApp.DisplayAlerts = False

    i = 0
    for chart in xlSheet1.ChartObjects():
        print chart.Name

        chart.CopyPicture()
        #Create new temporary sheet
        xlApp.ActiveWorkbook.Sheets.Add(After=xlApp.ActiveWorkbook.Sheets(3)).Name="temp_sheet" + str(i)
        temp_sheet = xlApp.ActiveSheet

        #Add chart object to new sheet.
        cht = xlApp.ActiveSheet.ChartObjects().Add(0,0,800, 600)
        #Paste copied chart into new object
        cht.Chart.Paste()
        #Export image
        cht.Chart.Export("chart" + str(i) + ".png")

        #This line is not entirely neccessary since script currently exits without saving
        temp_sheet.Delete()
        i = i+1

    xlApp.ActiveWorkbook.Close()
    #Restore default behaviour
    xlApp.DisplayAlerts = True

0

现在我会推荐使用excel2img库,它为我服务得很好。确保你已经安装了它(pip install excel2img)

import excel2img

excel2img.export_img("test.xlsx", "test.gif", "Sheet1", "MyNamedRange")

如果您不需要网格线 - 只需在Excel中隐藏它。

Git仓库:excel2img 了解更多信息。


Yomajo excel2img 在 Microsoft Excel 2016 上无法使用。您能否建议一个替代方案? - Python Bang
@PythonBang,你找到解决方案了吗? - ambigus9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接