获取 Excel 图表详细信息到 Python

时间:2021-06-29 04:53:40

标签: python excel linux openpyxl

我有一个 excel 文件,它在单独的工作表上有图表,并且在它们上面绘制了多个系列。我需要做的是使用 python 绘制完全相同的范围。我的范围是指以下内容:

enter image description here

有没有办法通过python访问这些信息?

1 个答案:

答案 0 :(得分:1)

试试这个代码:

选项 1 适用于所有工作表

import win32com.client as client


def series_output(chart):
    print(f'\tChart name is {chart.Name}')
    for sc in chart.SeriesCollection():
        print(f'\t\t{sc.Name}: {sc.Formula}')


xl = client.Dispatch('Excel.Application')
wb = xl.Workbooks.Open(r'c:\test\Charts.xlsm')
for sh in wb.Sheets:
    print(f'Processed sheet {sh.Name}')
    if sh.Type == -4100:  # it's chart sheet
        series_output(sh)
    elif sh.Type == -4167:  # it's worksheet with (possible) charts
        for ch in sh.ChartObjects():
            series_output(ch.Chart)
wb.Close(False)  # don't save & close workbook
xl.Quit()

选项 2 用于特定工作表

import win32com.client as client


def series_output(chart):
    print(f'\tChart name is {chart.Name}')
    for sc in chart.SeriesCollection():
        print(f'\t\t{sc.Name}: {sc.Formula}')


xl = client.Dispatch('Excel.Application')
wb = xl.Workbooks.Open(r'c:\test\Charts.xlsm')  # your own path\name
sh = wb.Sheets('Sheet1')  # your own worksheet name
print(f'Processed sheet {sh.Name}')
for ch in sh.ChartObjects():
    series_output(ch.Chart)
wb.Close(False)  # don't save & close workbook
xl.Quit()