从Excel导出图表作为使用Python的图像 [英] Export Charts from Excel as images using Python

查看:576
本文介绍了从Excel导出图表作为使用Python的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将图表从Excel导出为Python中的图像文件(JPG或ING)。我在看WIn32com。这是我到现在为止。

I have been trying to export the charts from Excel as an image file (JPG or ING) in Python. I am looking at the WIn32com. Here is what I have till now.

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()

这是我被卡住的地方。我需要将所选范围复制到一个文件。任何帮助或指向文档可以帮助我很多。

This is where I am stuck. I need to copy the selected range to a file now. Any help or pointers towards the doc can help me a lot.

我已经基于以下VBA脚本建模了上述代码:

I have modelled the above code based on the following VBA script:

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

推荐答案

我不得不看一些V BA的例子让这个工作。虽然我讨厌自己回答自己的问题,但是在这里可能需要这个人。

I had to look at some VBA examples to get this working. Although I hate answering my own questions, I am leaving this here for people who might need it.

    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()

这篇关于从Excel导出图表作为使用Python的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆