【问题标题】:Export Charts from Excel as images using Python使用 Python 将图表从 Excel 导出为图像
【发布时间】:2021-12-09 20:04:48
【问题描述】:

我一直在尝试将 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

【问题讨论】:

  • 我的建议是打破与 Excel 的联系。为什么要在 Excel 中绘制图表,然后使用 Python?使用 python 读取数据并使用 matplotlib 进行绘图很容易。
  • 不幸的是,早期的工作迫使我坚持使用 Excel。并且有 10 多张图表是从多张纸上绘制的。
  • 为什么不直接导出图表呢? Sheet 对象有一个ChartObjects 集合:每个ChartObject 都有一个包含ChartExport 方法。复制包含图表的范围,然后将其粘贴到空图表中似乎需要很长时间。

标签: python windows excel winapi win32com


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我知道这是一个老问题,但它帮助我走上了正确的轨道,所以我回来分享我完成的脚本,该脚本在工作表中找到所有图表并将它们导出为 .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
    

    【讨论】:

      【解决方案3】:

      对我来说效果很好:

      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)
      

      【讨论】:

      • 有没有办法可以导出到某个路径?
      • 我无法为此更改输出路径,有什么办法可以更改吗?
      【解决方案4】:

      现在我会推荐 excel2img 库,对我很有帮助。确保已安装(pip install excel2img)

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

      如果您不需要网格线 - 只需将其隐藏在 excel 中即可。

      git 代表:excel2img 了解更多信息。

      【讨论】:

      • Yomajo excel2img 不适用于 microsoft excel 2016。您能否提出替代方案?
      • @PythonBang 你找到解决方案了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 2022-01-17
      • 1970-01-01
      • 2014-09-24
      相关资源
      最近更新 更多