Python excel to jpg

So it seems there’s something weird going on with PIL ImageGrab.grabclipboard()

import win32com.client
from PIL import ImageGrab

o = win32com.client.Dispatch('Excel.Application')
o.visible = False

wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']

ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture()  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

When I run this, I notice that if I ctrl-V , the image is actually correctly saved on the clipboard, but my img variable returns None, meaning ImageGrab.grabclipboard() is somehow not working. Any ideas?

asked Jun 30, 2017 at 15:54

David Yang's user avatar

4

Here I have a solution which might help you.

import excel2img
excel2img.export_img("example.xlsx/example.csv","image.png/image.bmp","sheet!B2:H22")

This is working perfectly for me.

RobC's user avatar

RobC

22.2k20 gold badges69 silver badges79 bronze badges

answered Aug 12, 2019 at 9:03

Jagadeeswara Reddy P's user avatar

3

To clarify those comments of Florent B. and David Yang

Add optional parameter Format into .CopyPicture() will make ImageGrab.getclipboard() work as expected.

The following code will be
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format = 2)

Number 2 is xlBitmap, refer to https://learn.microsoft.com/en-us/office/vba/api/excel.range.copypicture

answered Jul 3, 2020 at 7:26

Shuu Terumi's user avatar

0

I just replaced ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture() by ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy() and it
worked perfectly.

So this is the entire code.

import win32com.client
from PIL import ImageGrab

o = win32com.client.Dispatch('Excel.Application')
o.visible = False

wb = o.Workbooks.Open(path)
ws = wb.Worksheets['Global Dash']

ws.Range(ws.Cells(1,1),ws.Cells(66,16)).Copy()  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

Dharman's user avatar

Dharman

29.9k22 gold badges82 silver badges132 bronze badges

answered Mar 10, 2022 at 14:48

tem's user avatar

1

I just tried the method posted in the comments under the question and it actually works!
Pay attention to use win32com.client.constants to get the xlBitmap.
In addition, my environment is Python 3.6 and I haven’t tried it again in Python 2.7.

win32c = win32com.client.constants
ws.Range(ws.Cells(1,1),ws.Cells(66,16)).CopyPicture(Format= win32c.xlBitmap)

img = ImageGrab.grabclipboard()
imgFile = os.path.join(path_to_img,'test.jpg')
img.save(imgFile)

answered Jun 8, 2018 at 7:56

Kn.Bk's user avatar

Kn.BkKn.Bk

214 bronze badges

1

This solution worked for me.
Try to start Excel with:

o = win32com.client.gencache.EnsureDispatch("Excel.Application")

Then use win32com.client.constants to get the xlBitmap

wb = o.Workbooks.Open(workbook_file_name)
ws = wb.Worksheets("Vs. Disk or Retrofit Chart View")
ws.Range(ws.Cells(22,1),ws.Cells(62,8)).CopyPicture(Format= win32com.client.constants.xlBitmap)  
img = ImageGrab.grabclipboard()
imgFile = os.path.join(os.getcwd(),'test.jpg')
img.save(imgFile)

answered Feb 12, 2020 at 7:14

Suraj Patil's user avatar

The best way to do it is:

import win32com.client
from PIL import ImageGrab

wb_file_name = 'Input.xlsx'
outputPNGImage = 'Output.png'

xls_file = win32com.client.gencache.EnsureDispatch("Excel.Application")

wb = xls_file.Workbooks.Open(Filename=wb_file_name)
xls_file.DisplayAlerts = False 
ws = wb.Worksheets("Desired_Tab")
ws.Range(ws.Cells(1,1),ws.Cells(15,3)).CopyPicture(Format= win32com.client.constants.xlBitmap)  # example from cell (1,1) to cell (15,3)
img = ImageGrab.grabclipboard()
img.save(outputPNGImage)
wb.Close(SaveChanges=False, Filename=wb_file_name)

answered Sep 21, 2021 at 15:09

TR Fernandes's user avatar

1

В комментариях к одному из моих прошлых видео о работе с Excel на Python меня спросили как сделать сохранение таблицы экселя в картинку.  Я погуглил, подумал и то что получилось в итоге оформил в виде небольшого скрипта на Python и снял пояснительное видео.

Исходный код выложен на гитхабе, но пусть и здесь будет лежать:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

# https://pillow.readthedocs.io/en/stable/handbook/tutorial.html

from PIL import ImageGrab

from config import get_path

# https://pypi.org/project/pywin32/

import win32com.client

def main():

    print(«I’m %s at %s» % (__name__, get_path(__name__)))

    xlsx_path = get_path(‘data’, ‘sample.xlsx’)

    # https://stackoverflow.com/questions/44850522/python-export-excel-sheet-range-as-image

    # https://docs.microsoft.com/ru-ru/office/vba/api/excel.application(object)

    client = win32com.client.Dispatch(«Excel.Application»)

    # https://docs.microsoft.com/ru-ru/office/vba/api/excel.workbooks

    wb = client.Workbooks.Open(xlsx_path)

    # https://docs.microsoft.com/ru-ru/office/vba/api/excel.worksheet

    # ws = wb.ActiveSheet

    ws = wb.Worksheets(«Sheet1»)

    # for v in ws.Range(«A1»): print(v)

    # https://docs.microsoft.com/ru-ru/office/vba/api/excel.range.copypicture

    ws.Range(«A1:D6»).CopyPicture(Format = 2)

    img = ImageGrab.grabclipboard()

    img.save(get_path(‘data’, ‘image.jpg’))

    wb.Close() # иначе табл будет открыта

    client.Quit()

Save ranges from Excel documents as images

Project description

Save ranges from Excel documents as images

Project details

Download files

Download the file for your platform. If you’re not sure which to choose, learn more about installing packages.

Source Distribution

Close

Hashes for excel2img-1.4.0.tar.gz

Hashes for excel2img-1.4.0.tar.gz

Algorithm Hash digest
SHA256 f96b1adab717ab196dc236d341f1ee5fa046f0f001051c9e468fd83b782b7737
MD5 89497a82d67ef75fa25dba69ad3c47e2
BLAKE2b-256 8cf5eb52c4bf63ab3e452f8d6a32dea93393d7936990837f731e961e6c18384d

Содержание

  1. Convert Excel Files to Image in Python
  2. Python Excel to Image Converter API#
  3. Python Excel to Image Conversion#
  4. Convert Excel to SVG Image in Python#
  5. Get a Free API License#
  6. Conclusion#
  7. Convert EXCEL to JPG via Python
  8. Export Excel spreadsheets to JPG format using Python APIs.
  9. Aspose.Cells for Python
  10. Overview
  11. Convert EXCEL to JPG Using Python
  12. Save EXCEL to JPG in Python Online for Free
  13. How to Convert EXCEL to JPG via Python
  14. Python library to convert EXCEL to JPG
  15. System Requirements
  16. EXCEL What is EXCEL File Format
  17. JPG What is JPG File Format
  18. Other Supported Conversions
  19. glexey/excel2img
  20. Sign In Required
  21. Launching GitHub Desktop
  22. Launching GitHub Desktop
  23. Launching Xcode
  24. Launching Visual Studio Code
  25. Latest commit
  26. Git stats
  27. Files
  28. README.rst
  29. About
  30. Resources
  31. License
  32. Stars
  33. Watchers
  34. Forks
  35. Releases
  36. Packages 0
  37. Languages
  38. Footer
  39. Convert EXCEL to JPG in Python
  40. High-speed Python library for converting EXCEL to JPG. Use our excel conversion API to develop high-level, platform independent software in Python. This is a professional software solution to import and export Excel, CSV, OpenOffice, PDF, HTML, image, and many other excel formats Aspose.Cells for Python via NET.
  41. Aspose.Cells for Python
  42. Overview
  43. Convert EXCEL to JPG in Python
  44. Save EXCEL to JPG in Python Online for Free
  45. How to Convert EXCEL to JPG
  46. Python library to convert EXCEL to JPG
  47. System Requirements
  48. EXCEL What is EXCEL File Format
  49. JPG What is JPG File Format
  50. Other Supported Conversions
  51. Преобразование EXCEL в JPG через Python
  52. Экспортируйте электронные таблицы Excel® в формат JPG с помощью Python API.
  53. Aspose.Cells for Python
  54. Overview
  55. Как преобразовать EXCEL в JPG с помощью Python
  56. Действия по преобразованию EXCEL в JPG через Python
  57. Системные Требования
  58. EXCEL Формат файла EXCEL
  59. JPG Формат файла JPG
  60. Другие поддерживаемые преобразования

Convert Excel Files to Image in Python

In various cases, Excel spreadsheets are required to be embedded in the web or desktop applications. One of the solutions in such cases is the conversion of Excel worksheets to image formats. In this article, you will learn how to convert Excel XLSX or XLS to PNG, JPEG, SVG, or other images in Python.

Python Excel to Image Converter API#

In order to convert Excel’s XLSX or XLS files to image formats, we will use Aspose.Cells for Python via Java. It is a spreadsheet manipulation API that lets you create, modify or convert Excel files. You can install the API using the following command.

Aspose.Cells for Python via Java supports conversion of Excel files to the following image formats:

Python Excel to Image Conversion#

The following are the steps to convert Excel files to an image format, i.e. PNG, JPEG, etc. in Python.

  • Load the Excel file using the Workbook class.
  • Create an instance of ImageOrPrintOptions class and specify the output image format.
  • Access the worksheet you want to convert using Workbook.getWorksheets().get(index) method.
  • Create a SheetRender object and initialize it with Worksheet and ImageOrPrintOptions objects.
  • Save each page of Excel worksheet as an image using SheetRender.toImage(pageIndex, fileName) method.

The following code sample shows how to convert an Excel worksheet to PNG image.

Convert Excel to SVG Image in Python#

The following are the steps to convert an Excel file to SVG in Python.

  • Load the Excel file using the Workbook class.
  • Create an instance of ImageOrPrintOptions class and specify the output image format.
  • Loop through the worksheets in the Excel file using Workbook.getWorksheets().getCount() method.
  • In each iteration, perform the following operations:
    • Create a SheetRender object and initialize it with Worksheet and ImageOrPrintOptions objects.
    • Save each page of the Excel worksheet as SVG using SheetRender.toImage(pageIndex, fileName) method.

The following code sample shows how to convert Excel to SVG in Python.

Get a Free API License#

You can use the API without evaluation limitations by requesting a free temporary license.

Conclusion#

In this article, you have learned how to convert Excel files to image formats in Python. The step-by-step guide and code samples demonstrated how to convert sheets in an Excel workbook to PNG and SVG formats. You can explore more about the Python spreadsheet API using the documentation. In case you would have any questions or queries, feel free to let us know via our forum.

Источник

Convert EXCEL to JPG via Python

Export Excel spreadsheets to JPG format using Python APIs.

Aspose.Cells for Python

Overview

Download from NuGet

Open NuGet package manager, search for and install.
You may also use the following command from the Package Manager Console.

Convert EXCEL to JPG Using Python

Save EXCEL to JPG in Python Online for Free

The following example demonstrates how to convert EXCEL to JPG in Python.

Follow the easy steps to convert EXCEL to JPG. Upload your EXCEL file, then simply save it as JPG file. For both EXCEL reading and JPG writing you can use fully qualified filenames. The output JPG content and formatting will be identical to the original EXCEL document.

How to Convert EXCEL to JPG via Python

Python developers can easily load & convert EXCEL to JPG in just a few lines of code.

  1. Load EXCEL file with an instance of Workbook
  2. Convert EXCEL to JPG by calling Workbook.save method

Python library to convert EXCEL to JPG

There are three options to install “Aspose.Cells for Python via Java” onto your system. Please choose one that resembles your needs and follow the step-by-step instructions:

  1. Install Aspose.Cells for Python via Java in Windows. See Documentation
  2. Install Aspose.Cells for Python via Java in Linux. See Documentation
  3. Install Aspose.Cells for Python via Java in macOS. See Documentation

System Requirements

Aspose.Cells for Python is platform-independent API and can be used on any platform (Windows, Linux and MacOS), just make sure that system have Java 1.8 or higher, Python 3.5 or higher.

  • Install Java and add it to PATH environment variable, for example: PATH=C:Program FilesJavajdk1.8.0_131; .
  • Install Aspose.Cells for Python from pypi, use command as: $ pip install aspose-cells .

EXCEL What is EXCEL File Format

XLSX is well-known format for Microsoft Excel documents that was introduced by Microsoft with the release of Microsoft Office 2007. Based on structure organized according to the Open Packaging Conventions as outlined in Part 2 of the OOXML standard ECMA-376, the new format is a zip package that contains a number of XML files. The underlying structure and files can be examined by simply unzipping the .xlsx file.

JPG What is JPG File Format

A JPEG is a type of image format that is saved using the method of lossy compression. The output image, as result of compression, is a trade-off between storage size and image quality. Users can adjust the compression level to achieve the desired quality level while at the same time reduce the storage size. Image quality is negligibly affected if 10:1 compression is applied to the image. The higher the compression value, the higher the degradation in image quality.

Other Supported Conversions

You can also convert EXCEL to many other file formats including few listed below.

Источник

glexey/excel2img

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

Save ranges from Excel documents as images

  1. Python 2.7, 3.3 or later
  2. pywin32
  3. Pillow >= 3.3.1
  4. Microsoft Excel (tested with Office 2013, on Windows 10)

Usage as python module

Usage from command line

Apache License 2.0

About

Save ranges from Excel documents as images

Resources

License

Stars

Watchers

Forks

Releases

Packages 0

Languages

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Convert EXCEL to JPG in Python

High-speed Python library for converting EXCEL to JPG. Use our excel conversion API to develop high-level, platform independent software in Python. This is a professional software solution to import and export Excel, CSV, OpenOffice, PDF, HTML, image, and many other excel formats Aspose.Cells for Python via NET.

Aspose.Cells for Python

Overview

Download from NuGet

Open NuGet package manager, search for and install.
You may also use the following command from the Package Manager Console.

Convert EXCEL to JPG in Python

How to convert EXCEL to JPG? With Aspose.Cells for Python via NET library, you can easily convert EXCEL to JPG programmatically with a few lines of code. Aspose.Cells for Python via NET is capable of building cross-platform applications with the ability to generate, modify, convert, render and print all Excel files.

Python Excel API not only convert between spreadsheet formats, it can also render Excel files as images, PDF, HTML, ODS, CSV, SVG, JSON, WORD, PPT and more, thus making it a perfect choice to exchange documents in industry-standard formats.

Save EXCEL to JPG in Python Online for Free

The following example demonstrates how to convert EXCEL to JPG in Python via NET.

Follow the easy steps to convert EXCEL to JPG. Upload your EXCEL file, then simply save it as JPG file. For both EXCEL reading and JPG writing you can use fully qualified filenames. The output JPG content and formatting will be identical to the original EXCEL document.

How to Convert EXCEL to JPG

Python developers can easily load & convert EXCEL to JPG in just a few lines of code.

  1. Install ‘Aspose.Cells for Python via .NET’.
  2. Add a library reference (import the library) to your Python project.
  3. Load EXCEL file with an instance of Workbook
  4. Convert EXCEL to JPG by calling Workbook.save method

Python library to convert EXCEL to JPG

We host our Python packages in PyPi repositories.

Install Aspose.Cells for Python from pypi, use command as: $ pip install aspose-cells-python .

And you can also follow the step-by-step instructions on how to install “Aspose.Cells for Python via .NET” to your developer environment.

System Requirements

Aspose.Cells for Python is platform-independent API and can be used on any platform (Windows, Linux), just make sure that system have Python 3.7 or higher.

EXCEL What is EXCEL File Format

XLSX is well-known format for Microsoft Excel documents that was introduced by Microsoft with the release of Microsoft Office 2007. Based on structure organized according to the Open Packaging Conventions as outlined in Part 2 of the OOXML standard ECMA-376, the new format is a zip package that contains a number of XML files. The underlying structure and files can be examined by simply unzipping the .xlsx file.

JPG What is JPG File Format

A JPEG is a type of image format that is saved using the method of lossy compression. The output image, as result of compression, is a trade-off between storage size and image quality. Users can adjust the compression level to achieve the desired quality level while at the same time reduce the storage size. Image quality is negligibly affected if 10:1 compression is applied to the image. The higher the compression value, the higher the degradation in image quality.

Other Supported Conversions

You can also convert EXCEL to many other file formats including few listed below.

Источник

Преобразование EXCEL в JPG через Python

Экспортируйте электронные таблицы Excel® в формат JPG с помощью Python API.

Aspose.Cells for Python

Overview

Download from NuGet

Open NuGet package manager, search for and install.
You may also use the following command from the Package Manager Console.

Как преобразовать EXCEL в JPG с помощью Python

Чтобы преобразовать EXCEL в JPG, мы будем использовать

API — многофункциональное, мощное и простое в использовании средство обработки и преобразования документов API для платформы Python.

Действия по преобразованию EXCEL в JPG через Python

Разработчики Python могут легко загружать и преобразовывать файлы EXCEL в JPG, написав всего несколько строк кода.

  1. Загрузите файл EXCEL с экземпляром книги1. Вызов метода Workbook.Save1. Передать выходной путь с расширением JPG в качестве параметра1. Проверить указанный путь для результирующего файла JPG

Системные Требования

Aspose.Cells для Python не зависит от платформы API и может использоваться на любой платформе (Windows, Linux и MacOS), просто убедитесь, что в системе установлена Java 1.8 или выше, Python 3,5 или выше.

  • Установите Java и добавьте его в переменную среды PATH, например: PATH=C:Program FilesJavajdk1.8.0_131; .- Установите Aspose.Cells для Python из пипи, используйте команду как: $ pip install aspose-cells .

EXCEL Формат файла EXCEL

XLSX — это хорошо известный формат для документов Microsoft Excel, который был представлен Microsoft с выпуском Microsoft Office 2007. Основанный на структуре, организованной в соответствии с соглашениями об открытой упаковке, как указано в части 2 стандарта OOXML ECMA-376, новый формат ZIP-пакет, содержащий несколько XML-файлов. Базовую структуру и файлы можно изучить, просто разархивировав файл .xlsx.

JPG Формат файла JPG

JPEG — это тип формата изображения, который сохраняется с использованием метода сжатия с потерями. Выходное изображение в результате сжатия представляет собой компромисс между размером хранилища и качеством изображения. Пользователи могут настроить уровень сжатия для достижения желаемого уровня качества и в то же время уменьшить размер хранилища. Качество изображения незначительно ухудшается, если к изображению применяется сжатие 10:1. Чем выше значение сжатия, тем выше ухудшение качества изображения.

Другие поддерживаемые преобразования

Вы также можете конвертировать EXCEL во многие другие форматы файлов, включая некоторые из перечисленных ниже.

Источник

Сохраните Excel-диаграмму Python как изображение

Привет всем, я не обновлял свой блог в течение долгого времени. Я был немного занят некоторое время. Компания подверглась большой обработке файлов Excel. Теперь я поделюсь с вами своим опытом, накопленным в моей работе.
Описание бизнеса: В это время моя основная работа:
  • Анализ Excel и запись целевого поля в базу данных (включая шифрование, HTML в файл Excel);
  • Получайте данные из базы данных, пишите в Excel, рисуйте картинки и сохраняйте картинки как;
  • Заполните сгенерированные изображения и рассчитанные другие поля данных в шаблоне слова, чтобы сформировать документ отчета;
Требование одно:Разбор Excel, запись целевого поля в базу данных (включая шифрование, HTML в файл Excel)Вы можете сослаться на мой предыдущий блог, в котором есть подробные инструкции
Далее я в основном представлю бизнес-требования для всех, как написать данные, чтобы превзойти их, затем скопировать изображение и сохранить изображение как: из-за реальных потребностей бизнеса я нашел много информационных блогов и, наконец, нашел хорошее решение. Я полагаю, что вы также можете столкнуться с такими же проблемами, как я, когда вы учитесь.

Процесс реализации логики:

Первый шаг: (создайте новый файл data.xlsx, вставьте картинку, как наш файл шаблона, поле данных показано на рисунке)

Второй шаг: измените данные ячеек B2 на B8 на [20, 30, 20, 30, 40, 50, 35], которые можно изменить в соответствии с вашими потребностями.

Шаг 3: Скопируйте область D1: I12 как изображение, переместите изображение в K1, эффект будет следующим:

Шаг 4. Сохраните изображение непосредственно как

Шаг 5: Сохраните файл как copy.xlsx, данные папки

Полный код: (первое издание)

import win32com.client as win32 # Открыть файл Excel
from PIL import ImageGrab   # Для получения скопированных картинок

root_path = "XXX"

excel = win32.Dispatch('Excel.Application') # Получите Excel
wb = excel.Workbooks.Open(root_path+'data.xlsx') # Открыть файл Excel
ws = wb.Worksheets('Sheet1')        # Get Sheet1

score = [20,30,20,30,40,50,35]      # Нужно написать данные оценки Excel
# Обход Excel для записи данных в ячейки
for i in range(2, len(score)+2):
    Range = 'B' + str(i)    # Ячейки с B2 по B8
    ws.Range(Range).Value = score[i-2]  # Напишите значение
ws.Range('D1:I12').CopyPicture()    # Копировать D1: область изображения I12
ws.Paste(ws.Range('K1'))    # Переместить картинку в K1
ws.Shapes('Picture 1').Copy()    # Скопируйте движущееся изображение Изображение 1
img = ImageGrab.grabclipboard()  # Получить данные изображения
img.save(root_path+'Picture 1.png') # Сохранить изображение как

wb.SaveAs(root_path+'copy.xlsx') # Сохраните файл excel как copy.xlsx
wb.Close()

Специальное примечание: когда код выполняется для ws.Shapes (‘Picture 1’). Copy (), он может сообщить, что определение изображения не найдено. Сначала я думал об изменении имени изображения, которое мы скопировали с помощью функции метода, а затем о копировании изображения Однако после некоторой борьбы подходящий метод не был найден. Если великий бог знает, оставьте сообщение и будьте благодарны.

Но, в конце концов, есть решение только для справки, мы сначала закомментируем следующие строки кода

ws.Shapes('Picture 1').Copy()    # Скопируйте движущееся изображение Изображение 1
img = ImageGrab.grabclipboard()  # Получить данные изображения
img.save(root_path+'Picture 1.png') # Сохранить изображение как

Затем запустите код. После успешного запуска файл copy.xlsx будет успешно создан. Мы дважды щелкаем, чтобы открыть файл. Клик мышью на изображение, которое мы успешно скопировали. В верхнем левом углу отобразится имя сгенерированного изображения: Рисунок 1; версия с другим именем Он может отличаться, поэтому при возникновении ошибки вы можете изменить имя изображения в соответствии с этим процессом.

Полный код: (Ultimate Edition)

Идеальная ошибка при копировании изображений, просто переименуйте выбранную область (спасибо @vhills за обмен)

import win32com.client as win32 # Открыть файл Excel
from PIL import ImageGrab   # Для получения скопированных картинок

root_path = "D:\Luzaofa_Class\"

excel = win32.Dispatch('Excel.Application') # Получите Excel
wb = excel.Workbooks.Open(root_path+'data.xlsx') # Открыть файл Excel
ws = wb.Worksheets('Sheet1')        # Get Sheet1

score = [20,30,20,30,40,50,35]      # Нужно написать данные оценки Excel
# Обход Excel для записи данных в ячейки
for i in range(2, len(score)+2):
    Range = 'B' + str(i)    # Ячейки с B2 по B8
    ws.Range(Range).Value = score[i-2]  # Напишите значение
ws.Range('D1:I12').CopyPicture()    # Копировать D1: область изображения I12
ws.Paste(ws.Range('K1'))    # Переместить картинку в K1

new_shape_name = 'luzaofa'
***excel.Selection.ShapeRange.Name = new_shape_name***    # Выберите область для переименования

ws.Shapes(new_shape_name).Copy()    # Скопируйте движущееся изображение Изображение 1
img = ImageGrab.grabclipboard()  # Получить данные изображения
img.save(root_path + new_shape_name + '.png') # Сохранить изображение как

wb.SaveAs(root_path + 'copy.xlsx') # Сохраните файл excel как copy.xlsx
wb.Close()

Спасибо, у меня будет время поделиться с вами файлом шаблона работы с Python Word, чтобы сформировать отчетный документ, выучить и накопить, и поддержать вас.

В настоящее время я работаю над сценарием Python, который сохраняет снимки экрана из файла Excel с помощью модуля excel2image.

Мой код довольно прост:

import excel2img
excel2img.export_img(Workpath + "/" + "CB_TEMP.xlsx", "alarm_BB1.png", "Deckblatt", "A2:C20")

К сожалению, я всегда получаю следующее сообщение об ошибке:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-a119e849f4d5> in <module>
----> 1 excel2img.export_img(Workpath + "/" + "CB_TEMP.xlsx", "alarm_BB1.png", "Deckblatt", "A2:C20")

~anaconda3libsite-packagesexcel2imgexcel2img.py in export_img(fn_excel, fn_image, page, _range)
    111 
    112         # See http://stackoverflow.com/a/42465354/1924207
--> 113         for shape in rng.parent.Shapes: pass
    114 
    115         xlScreen, xlPrinter = 1, 2

~anaconda3libsite-packageswin32comclient__init__.py in __getattr__(self, attr)
    471                 args=self._prop_map_get_.get(attr)
    472                 if args is None:
--> 473                         raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
    474                 return self._ApplyTypes_(*args)
    475 

AttributeError: '<win32com.gen_py.Microsoft Excel 16.0 Object Library.Range instance at 0x2460934736048>' object has no attribute 'parent'

Я уже пробовал несколько обходных путей, но не могу заставить его работать. Иногда это работает как по волшебству, но в основном только после перезагрузки и удаления данных в C: / Users / patrick / AppData / Temp / gen_py.

У меня такое ощущение, что что-то противоречит в коде модуля win32com, который я использую в функции перед преобразованием файла XLSB в файл XLSX:

def ConvertExcel(excel_filepath, Workpath):
    excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
    xlsb_doc = excel.Workbooks.Open(os.path.abspath(excel_filepath))
    excel_sheets = os.path.abspath(Workpath) + "\CB_TEMP.xlsx"
    xlsb_doc.SaveAs(excel_sheets, 51)
    xlsb_doc.Close()
    excel.Quit()
    del excel
    return excel_sheets

Может кто-нибудь мне поможет?

С уважением, Патрик

1 ответ

Лучший ответ

Я исправил это, сбросив модуль excel2img.

Я написал новый код в xlwings с Pillow, который работает даже быстрее, чем в excel2img:

import xlwings as xw
from PIL import ImageGrab

try:
    excel_app = xw.App(visible=False)
    excel_book = excel_app.books.open(excel_filepath)

    for image in df_img.index:
        excel_book.sheets[df_img.at[image, "sheet_name"]][
            df_img.at[image, "Range"]].copy(destination=None)
        img = ImageGrab.grabclipboard()
        img.save(df_img.at[image, "Bild"], 'JPEG')
    excel_book.close()
    excel_app.quit()
    excel_app.kill()

except:
    pass


0

Hyperrick
21 Мар 2021 в 08:48

Понравилась статья? Поделить с друзьями:
  • Python pandas export to excel
  • Python excel read and write
  • Python pandas excel форматирование
  • Python pandas excel пример
  • Python excel read all sheets