Export Charts from Excel as images using Python

前端 未结 5 625
灰色年华
灰色年华 2020-12-01 10:20

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.

impor         


        
5条回答
  •  [愿得一人]
    2020-12-01 10:46

    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().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()
        # Delete the sheet
        cht.Delete()
        excel.ActiveSheet.Delete()
        # Close the book
        excel.ActiveWorkbook.Close()
    

提交回复
热议问题