Save cellrange from excel spreadsheet as image in python - python-3.x

I am currently working on a Python script that saves screenshots from an Excel file using the excel2image module.
My code is pretty easy:
import excel2img
excel2img.export_img(Workpath + "/" + "CB_TEMP.xlsx", "alarm_BB1.png", "Deckblatt", "A2:C20")
Unfortunately I always get the following error message:
---------------------------------------------------------------------------
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")
~\anaconda3\lib\site-packages\excel2img\excel2img.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
~\anaconda3\lib\site-packages\win32com\client\__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'
I have already tried several workarounds but I can't get it to work. Sometimes it works like magic, but mostly only after a reboot and deleting the data in C:/Users/patrick/AppData/Temp/gen_py.
I have a feeling something is clashing in the code with the win32com module I use in a function before to convert an XLSB file to an XLSX file:
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
Maybe anybody can help me out?
Kind regards,
Patrick

I fixed this by dropping the excel2img module.
I wrote the code new in xlwings with Pillow which works even faster than in 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

Related

AttributeError: module 'ee' has no attribute 'Reducer'

I'm learning GEE recently with accessing VPN but met error as show below:
#######################################################
import ee
import geemap
import os
geemap.set_proxy(port=7890)
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'
Map = geemap.Map()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In [5], line 7
5 os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
6 os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'
----> 7 Map = geemap.Map()
File ~\anaconda3\envs\gee\lib\site-packages\geemap\geemap.py:173, in
Map.__init__(self, **kwargs)
171 self.roi_end = False
172 if kwargs["ee_initialize"]:
--> 173 self.roi_reducer = ee.Reducer.mean()
174 self.roi_reducer_scale = None
176 # List for storing pixel values and locations based on user-drawn
geometries.
AttributeError: module 'ee' has no attribute 'Reducer'
##############################################################
I checked too many answers through forum but nothing work. Is there anyone who knows the reason? really appreciate it!

FileNotFoundError: [Errno 2] No such file or directory: in jupyter notebook

from scipy.io import wavfile
train_audio_path = 'E:/'
filename = 'file_example_WAV_1MG'
sample_rate, samples = wavfile.read(train_audio_path + filename)
print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))
FileNotFoundError Traceback (most recent call last)
<ipython-input-27-cd74bbc41446> in <module>
3 train_audio_path = 'E:/'
4 filename = 'file_example_WAV_1MG'
----> 5 sample_rate, samples = wavfile.read(train_audio_path + filename)
6 print('sample rate : {}, samples.shape : {}'.format(sample_rate, samples.shape))
E:\anaconda\lib\site-packages\scipy\io\wavfile.py in read(filename, mmap)
262 mmap = False
263 else:
--> 264 fid = open(filename, 'rb')
265
266 try:
FileNotFoundError: [Errno 2] No such file or directory: 'E:/file_example_WAV_1MG'
I have a problem with my code. I tried to do everything but failed. I have no idea why this error is made. I changed path to everywhere from c to e but still not working at all. what's wrong in my code?
Try
train_audio_path = 'E:\' OR 'E:\\'
change the direction of '\'
And don't forget to add the extension of your image file as well (i.e., jpg,png or any other). I also get this error multiple times in windows.Hope it helps.
I think you are missing the extension. Perhaps file_example_WAV_1MG.wav ?
Check it on your computer.

Openpyxl version 2.5.11 issue

I updated yesterday with Openpyxl library to version 2.5.11. Now, when i simply open an excel workbook (it's a xlsx file without macros), I get the following strange error message that I didn't have when I was opening the exact same file yesterday before I updated the library:
Code:
tips = r"NTipsPerf6b.xlsm"
wb = openpyxl.load_workbook(tips)
and this is the traceback:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-16-980c37a8c9f7> in <module>()
----> 1 wb = openpyxl.load_workbook(tips)
C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\reader\excel.py in load_workbook(filename, read_only, keep_vba, data_only, guess_types, keep_links)
291 ws._rels = [] # reset
292
--> 293 parser.assign_names()
294
295 #wb._differential_styles.styles = [] # tables may depened upon dxf
C:\ProgramData\Anaconda3\lib\site-packages\openpyxl\packaging\workbook.py in assign_names(self)
104 reserved = defn.is_reserved
105 if reserved in ("Print_Titles", "Print_Area"):
--> 106 sheet = self.wb._sheets[defn.localSheetId]
107 if reserved == "Print_Titles":
108 rows, cols = _unpack_print_titles(defn)
IndexError: list index out of range
if anyone has any clue on how to fix it that would be much appreciated. Thanks

Converting a generator into a list, but getting Error: '_io.TextIOWrapper' object has no attribute 'decode' (python 3.6.4)

I am working with a text in utf-8.
I want to tokenize it and then convert it into a list.
However I get the following error.
import nltk, jieba, re, os
with open('file.txt') as f:
tokenized_text = jieba.cut(f,cut_all=True)
type(tokenized_text)
generator
word_list = list(tokenized_text)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-5-16b25477c71d> in <module>()
----> 1 list(new)
~/anaconda3/lib/python3.6/site-packages/jieba/__init__.py in cut(self, sentence, cut_all, HMM)
280 - HMM: Whether to use the Hidden Markov Model.
281 '''
--> 282 sentence = strdecode(sentence)
283
284 if cut_all:
~/anaconda3/lib/python3.6/site-packages/jieba/_compat.py in strdecode(sentence)
35 if not isinstance(sentence, text_type):
36 try:
---> 37 sentence = sentence.decode('utf-8')
38 except UnicodeDecodeError:
39 sentence = sentence.decode('gbk', 'ignore')
AttributeError: '_io.TextIOWrapper' object has no attribute 'decode'
I understand the problem lies somewhere in the jieba package.
I also tried to change the code into
with open('file.txt') as f:
new = jieba.cut(f,cut_all=False)
but got the same result.
jieba.cut takes a string, not a file. This is explained in the readme.

Python 3.4 plistlib doesn't work (str vs bytes errors)

So, I started on a new toy project and decided I'd use Python 3 for the first time...
In [1]: import plistlib
In [2]: with open("/Volumes/Thunderbay/CURRENT/Music/iTunes/iTunes Library.xml") as itl:
library = plistlib.load(itl)
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-6459a022cb71> in <module>()
1 with open("/Volumes/Thunderbay/CURRENT/Music/iTunes/iTunes Library.xml") as itl:
----> 2 library = plistlib.load(itl)
3
/usr/local/Cellar/python3/3.4.3_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plistlib.py in load(fp, fmt, use_builtin_types, dict_type)
984 fp.seek(0)
985 for info in _FORMATS.values():
--> 986 if info['detect'](header):
987 P = info['parser']
988 break
/usr/local/Cellar/python3/3.4.3_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plistlib.py in _is_fmt_xml(header)
556
557 for pfx in prefixes:
--> 558 if header.startswith(pfx):
559 return True
560
TypeError: startswith first arg must be str or a tuple of str, not bytes
hmm ok, let's give it a hint:
In [3]: with open("/Volumes/Thunderbay/CURRENT/Music/iTunes/iTunes Library.xml") as itl:
library = plistlib.load(itl, fmt=plistlib.FMT_XML)
...:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-ef5f06b44ec2> in <module>()
1 with open("/Volumes/Thunderbay/CURRENT/Music/iTunes/iTunes Library.xml") as itl:
----> 2 library = plistlib.load(itl, fmt=plistlib.FMT_XML)
3
/usr/local/Cellar/python3/3.4.3_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plistlib.py in load(fp, fmt, use_builtin_types, dict_type)
995
996 p = P(use_builtin_types=use_builtin_types, dict_type=dict_type)
--> 997 return p.parse(fp)
998
999
/usr/local/Cellar/python3/3.4.3_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plistlib.py in parse(self, fileobj)
323 self.parser.EndElementHandler = self.handle_end_element
324 self.parser.CharacterDataHandler = self.handle_data
--> 325 self.parser.ParseFile(fileobj)
326 return self.root
327
TypeError: read() did not return a bytes object (type=str)
plistlib is in the standard library, but from the problems above I have the feeling it has not actually been converted to Python 3?
Anyway, my actual question: is it possible to open an XML plist file with plistlib in Python 3.4.3?
surely I'm missing something obvious here perhaps... just noticed the Py2 version of plistlib (which works!) has a different interface, so someone has actually modified the code of the library for inclusion with Py3...
Thanks to #J Presper Eckert for giving me a clue about what to look for...
I then found this article:
http://python-notes.curiousefficiency.org/en/latest/python3/text_file_processing.html#the-binary-option
which suggests the answer is simply to open the file in binary mode, tried it and it works!
with open("/Volumes/Thunderbay/CURRENT/Music/iTunes/iTunes Library.xml", 'rb') as itl:
library = plistlib.load(itl)
Got same error message using python 3.4.3 against .plist file ( mac property list, configuration file in xml ).
Try this (worked for me):
copy plist / xml file to new file.
change new file extension to '.txt'
open newfile.txt in textEdit (mac), notepad++(win) or similar
save as .txt file with UTF-8 encoding & plaintext only.
Now, when you read newfile.txt, you won't see "startswith first arg must be str or a tuple of str, not bytes".
Cheers

Resources