【发布时间】:2021-02-14 19:13:32
【问题描述】:
我对编码完全陌生(只是为了好玩,希望能节省一些工作时间),我一直在努力让我的第一行代码正常工作。
具体来说,我希望我的代码打开某个 Excel 工作簿,找到某些实际上是图表的工作表(每个工作表中只有一个图表)并将它们打印为特定文件夹中的 pdf/jpeg 文件。我选择了 ExportAsFixedFormat,但遇到了以下错误。
AttributeError: 'Chartsheet' object has no attribute 'ExportAsFixedFormat'
你能帮帮我吗?有什么方法可以打印/保存图表吗?
我浏览了 Chartsheet 对象的方法,但找不到任何有用的东西。我确定我错过了什么。
关于我的配置的一些信息:
Windows 10 家庭版 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()
【问题讨论】:
-
这可能会对您有所帮助:win32 ExportAsFixedFormat Error.
-
感谢您的帮助,但其他帖子中的链接已过期。无论如何,我发现 Worksheet 对象上的操作也会给我带来错误,就像我首先提到的那样。例如“AttributeError: 'Workbook' 对象没有属性 'SaveAs'”
-
感谢@ack,非常感谢您对此提供的帮助。我根据您链接的第二篇文章尝试了一些东西,但仍然没有...我收到此错误:“AttributeError:'
' object has no attribute 'WorkSheets' " -
请更新您的问题:Windows 版本、Office (Excel) 版本、python(32b?64b?)和 win32com 版本。
标签: python excel printing worksheet