首页 > 解决方案 > 如何使用 Python 从 Excel Chartsheet 打印图表

问题描述

我对编码完全陌生(这只是为了好玩,希望能节省一些工作时间),我一直在努力让我的第一行代码工作。
具体来说,我希望我的代码打开某个 Excel 工作簿,找到某些实际上是图表的工作表(每个工作表中只有一个图表)并将它们打印为特定文件夹中的 pdf/jpeg 文件。我选择了 ExportAsFixedFormat,但遇到了以下错误。

AttributeError: 'Chartsheet' object has no attribute 'ExportAsFixedFormat'

请你帮助我好吗?有什么方法可以打印/保存图表吗?
我浏览了 Chartsheet 对象的方法,但找不到任何有用的东西。我确定我错过了一些东西。

关于我的配置的一些信息:
Windows 10 Home x64
Excel for Microsoft 365 MSO (16.0.13628.20318) 64 位
Python 3.8 32 位
Pywin32 版本 227

在我遇到问题的代码块下方。
[编辑]:在我编写的整个代码下方,可能错误不在我认为的位置。
提前谢谢你,对不起我的英语不好。

首先,我进口了很多东西,我知道我很可能只需要其中的一半。

import plotly
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import win32com.client as win32
import openpyxl
import os, sys
import math
import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl import chart
from openpyxl import chartsheet
from openpyxl.chartsheet.publish import WebPublishItem, WebPublishItems
from openpyxl.drawing.spreadsheet_drawing import SpreadsheetDrawing
#from .drawings import find_images
from openpyxl.chartsheet import Chartsheet
import openpyxl.chart
import win32com.client
from pdf2image import convert_from_path
from pathlib import Path
import xlsxwriter

这是我写的代码:

path_filePy = Path(__file__).resolve()
current_folder = path_filePy.parent

image_folder_name = "Immages"
image_folder_path = os.path.join(current_folder, image_folder_name)  
try:  
    os.mkdir(image_folder_path)  
except OSError:
    files = os.listdir(image_folder_path)
    for f in files:
        os.remove(image_folder_path + '\\'+ f)

folder_list = os.listdir(current_folder)
excel_list=[]
for l in folder_list:
    if l.endswith('.xlsx'):
        excel_list.append(l)

chartsheets_names=['Chartsheet1', 'Chartsheet2', 'Chartsheet3', 'Chartsheet4']

excel = win32.gencache.EnsureDispatch('Excel.Application')

for excelfile in excel_list:    
    wb = load_workbook(os.path.join(current_folder, excelfile))      
    for sheet in chartsheets_names:    
        ws=wb[sheet]   
        image_file_name = excelfile[:-5]+'_'+sheet+'.pdf'        
        image_file_path = os.path.join(image_folder_path,image_file_name)        
        ws.ExportAsFixedFormat(0, image_file_path)                     
        convert_from_path(image_file_path, dpi=300, output_folder=image_folder_path,fmt='jpeg')
    wb.Close()

标签: pythonexcelprintingworksheet

解决方案


我最终得到了我想要的东西。下面是我现在使用的代码,也许它对其他人也有帮助。我想我在搞乱与 win32com 相关的代码和与 openpxl 相关的代码。

现在我希望我的Chartsheets在打印之前伸展到整个打印区域(我试图将边距设置为零,它不起作用)。我想我应该使用wb_sheet.PageSetup.ChartSizevalue FullPage,但我不知道如何分配它。

import os
import sys  
from pathlib import Path  
import win32com.client as w3c
from pdf2image import convert_from_path

# find the parent folder of the .py file
path_filePy = Path(__file__).resolve()
current_folder = path_filePy.parent
print(current_folder)

# create the destination folder or empty it if existing
image_folder_name = "Immages"
image_folder_path = os.path.join(current_folder, image_folder_name)  
#print(image_folder_path)
try:  
    os.mkdir(image_folder_path)  
except OSError:
    files = os.listdir(image_folder_path)
    for f in files:
        os.remove(image_folder_path + '\\'+ f)

# list of file in the folder
folder_list = os.listdir(current_folder)

# list of only *.xlsx files
excel_list=[]
for l in folder_list:
    if l.endswith('.xlsx'):
        excel_list.append(l)

# listof sheets' names I want to print
chartsheets_names=['Sheet1', 'Sheet2', 'Sheet3', 'Sheet4']

o = w3c.Dispatch("Excel.Application")
o.Visible = False

# for each sheet names as in my list, in each xlsx file, it prints in both pdf and jpeg
for excel_file in excel_list:
    try:
        wb_path = os.path.join(os.path.abspath(current_folder), excel_file)    
        wb = o.Workbooks.Open(wb_path)            
        for wb_sheet in wb.Sheets: 
            if wb_sheet.Name in chartsheets_names:
                path_to_pdf = os.path.join(os.path.abspath(image_folder_path), excel_file[:-5] + ' - ' + str(wb_sheet.Name) + '.pdf') 
                wb_sheet.SaveAs(path_to_pdf, FileFormat=57)
                convert_from_path(
                    path_to_pdf, # the input pdf file
                    dpi=300, 
                    output_folder=image_folder_path, 
                    fmt='jpeg',
                    output_file=str(excel_file[:-5] + ' - ' + str(wb_sheet.Name)),               
                    poppler_path = r"C:\where\your\poppler\bin folder is", 
                    use_pdftocairo=False)  
            else: next
        wb.Close(False) 
    except OSError:
        next
o.Quit

`


推荐阅读