python - 使用 Python 将 Excel 中的图表导出为图像

标签 python windows excel winapi win32com

我一直在尝试将图表从 Excel 导出为 Python 中的图像文件(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

最佳答案

我必须查看一些 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()

关于python - 使用 Python 将 Excel 中的图表导出为图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11110752/

相关文章:

windows - 神秘的 git 行为

python - 将参数传递给 cursor.execute() 时在 pyodbc 中出现 UnicodeDecodeError,但在将参数直接写入字符串时却不会

sql - Excel Vba - 在 sql 字符串中使用撇号

vba - 重命名文件夹 vba 中的文件

windows - IIS:对不在域中的客户端计算机使用 Kerberos

python - lxml 解析原子 - 空结果?

python - 使用 Git-Bash 在 Windows 中激活虚拟环境

python - 生成 PyQt 图例

c# - 通过 .NET 源中的公式将数据提取到 Excel 电子表格中的适当技术是什么?

python - 如何重新激活django用户