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-to-save-save-excel-excel-range-as-image-iusing.html
对于我来说,这效果很好:
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)
或此:
我必须查看一些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()
我知道这是一个古老的问题,但它有助于使我走上正确的轨道,所以我回来分享了我的完成脚本,该脚本在工作表中找到所有图表并将其导出为.png。 上面的脚本可以工作,但是由于它仅复制工作表中的范围,因此您根据图的图表确切。
现在,我会推荐Excel2img图书馆,为我服务。确保已安装它(PIP安装Excel2IMG)
如果您不需要网格线 - 只需将其隐藏在Excel中。
git代表:Excel2img要了解更多。
app = xw.App(visible=False)
wb = app.books.open(excel_file)
try:
for sheet in wb.sheets:
chart_count = 1
for chart in sheet.charts:
# Save each chart as an image
chart.to_pdf(image_path)
chart_count += 1
finally:
wb.close()
app.quit()
def crop_excel_images_from_pdf(pdf_path, dpi=300):
pdf_doc = fitz.open(pdf_path)
for page_num in range(len(pdf_doc)):
page = pdf_doc[page_num]
zoom = dpi / 72 # 72 dpi is default
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
cv_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
gray = cv2.cvtColor(cv_img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 30, 150)
contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
largest_contour = max(contours, key=cv2.contourArea)
x, y, w, h = cv2.boundingRect(largest_contour)
cropped = cv_img[y:y+h, x:x+w]
base_name = os.path.splitext(os.path.basename(pdf_path))[0]
output_path = pdf_path.replace('.pdf', f'_page{page_num+1}.png')
cv2.imwrite(output_path, cropped)
else:
continue