복붙노트

[PYTHON] Excel에서 차트를 파이썬을 사용하여 이미지로 내보내기

PYTHON

Excel에서 차트를 파이썬을 사용하여 이미지로 내보내기

저는 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

해결법

  1. ==============================

    1.나는 이것이 낡은 질문 인 줄 알았지 만 나를 올바른 길로 인도하는 데 도움이되어 워크 시트의 모든 차트를 찾아서 .png로 내 보낸 완성 된 스크립트를 다시 공유했습니다. 위의 스크립트는 작동 할 수 있지만 워크 시트 내의 범위를 복사하기 때문에 정확히 그 위치에있는 그래프에 의존하게됩니다.

    나는 이것이 낡은 질문 인 줄 알았지 만 나를 올바른 길로 인도하는 데 도움이되어 워크 시트의 모든 차트를 찾아서 .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
    
  2. ==============================

    2.이 작업을 수행하려면 몇 가지 VBA 예제를 살펴보아야했습니다. 내 자신의 질문에 답하는 것이 싫지만, 필자는이 질문을 필요로하는 사람들에게 남겨두고 있습니다.

    이 작업을 수행하려면 몇 가지 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()
    
  3. ==============================

    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. from https://stackoverflow.com/questions/11110752/export-charts-from-excel-as-images-using-python by cc-by-sa and MIT license