How to take picture with webcam from excel? - excel

I would like to take a picture using a webcam from excel macros, and I am a complete beginner when it comes to excel. I tried to follow other sources on the internet, but I can't even type in "Public Class Form1" without getting an error. What I did was I inserted a button into a spreadsheet, clicked "New," then replaced the sub data that comes with the button with code I found on the internet, and I just have tons of red lines throughout the code.
I looked at this post and its answers, but none of it works because, as I've said, excel doesn't want to work. If it's possible for you guys to give me more baby-step instructions (use this button and not that button, you gotta type "Public Class Form1" then pray to the gods for it to work instead of just pressing enter, stuff like that), that would help me greatly.
Visual Basic Connect to Webcam and Save Picture to File
Me not knowing how to terminate line. I tried &HD and &HA since that's a solution from microsoft, but that obviously didn't work.

The answer is don't try to do the whole thing from excel. In excel, assign a macro to a button. The code in that macro will be:
Sub RunPython()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExe = """PATH TO PYTHON.EXE"""
PythonScript = "PATH TO PYTHON CODE THAT NEEDS TO BE RUN"
objShell.Run PythonExe & PythonScript
End Sub
In Python 3, you, use the following code:
from cv2 import *
cam = VideoCapture(0) # 0 -> index of camera
s, img = cam.read()
if s: # frame captured without any errors
namedWindow("cam-test", WINDOW_NORMAL)
imshow("cam-test",img)
waitKey(1000)
destroyWindow("cam-test")
imwrite("filename.jpg",img) #save image
Credit:
Using Excel to use Python: https://stackoverflow.com/a/60658227/9582521
Using Python to use Webcam: https://stackoverflow.com/a/11094891/9582521

Related

Python - process ended with exit code 3221225477

I've searched on this forum for a possible workaround, and tried my best, but none is working. below is the issue. I've a function which process websocket data and dump into an excel
I tried to use a wrapper/loop around the function, but still its failing.
I am utilizing, xlwings to copy data to the excel as below
def websocket_data_process():
xw.Book(xcelfile).sheets[shets1].range('A40').options(index=False).value = futDf
----where futDf is pandas datafrme
The issue is whenever, I am editing the excel at 'A40' Range manually (while the funcion is running), I am getting error like process ended with exit 3221225477. (I googled and came to its a access denied issue). Is there any way that I can workaround this crash and again resume the function, once editing is down..
Not sure if this is what you want. You can ask for a pause. The solution below will only work with windows.
import os
os.system("pause")
or this will work with any system.
input('Press <ENTER> to continue')
Of course you need an statement such as
for i in range(50):
rng = f'A{i+1}'
if rng == 'A40':
input('Press <ENTER> to continue')
# Do your things here ...
thanks for the response, but I resolved it,
The issue happens because the xlwings trying to access the existing excel which is either locked or not available to access it.
solution: I've created an instance of Excel with xlwings context manager and provided full permissions to the account which is running the excel and it's been resolved.

How to keep the share properties of an excel with python openpyxl?

I have trouble trying to keep the sharing properties of an excel. I tried this :Python and openpyxl is saving my shared workbook as unshared but the part of vout just cancels all the modification I made with the script
To explain the problem :
There's an excel file that is shared in which people can do some modification
Python reads and writes on it
When I save the workbook in the excel file, it automatically either drops the sharing property or when I try to keep it, it just doesn't do any modification
Can someone help me please ?
I'll get a little more precise, as requested.
The sharing mode is the one Microsoft provides. You can see the button below:
Share button Excel
The excel is stored on a server. Several users can write on it at the same time but when I launch my script, it stops automatically the sharing property, so everyone that is writing on it just can't do modification anymore and every modif they did is lost.
First I treated my Excel normally :
DLT=openpyxl.load_workbook(myPath)
ws=DLT['DLT']
...my modifications on ws...
DLT.save()
DLT.close()
But then I tried this (Python and openpyxl is saving my shared workbook as unshared)
DLT=openpyxl.load_workbook(myPath)
ws=DLT['DLT']
zin = zipfile.ZipFile(myPath, 'r')
buffers = []
for item in zin.infolist():
buffers.append((item, zin.read(item.filename)))
zin.close()
...my modif on ws...
DLT.save()
zout = zipfile.ZipFile(myPath, 'w')
for item, buffer in buffers:
zout.writestr(item, buffer)
zout.close()
DLT.close()
The second one just doesn't save my modification on ws.
The thing I would like to do, is not to get rid of the sharing property. I would need to keep it while I write on it. Not sure if it is possible. I have one alternative solution that is to use another file, and just copy/paste by hand the new data from this file to the DLT one.
well... after playing with it back and forth, for some weird reason zipfile.infolist() does contains the sheet data as well, so here's my way to fine tune it, using the shared_pyxl_save example the previous gentleman provided
basically instead of letting the old file overriding the sheet's data, use the old one
def shared_pyxl_save(file_path, workbook):
"""
`file_path`: path to the shared file you want to save
`workbook`: the object returned by openpyxl.load_workbook()
"""
zin = zipfile.ZipFile(file_path, 'r')
buffers = []
for item in zin.infolist():
if "sheet1.xml" not in item.filename:
buffers.append((item, zin.read(item.filename)))
zin.close()
workbook.save(file_path)
""" loop through again to find the sheet1.xmls and put it into buffer, else will show up error"""
zin2 = zipfile.ZipFile(file_path, 'r')
for item in zin2.infolist():
if "sheet1.xml" in item.filename:
buffers.append((item, zin2.read(item.filename)))
zin2.close()
#finally saves the file
zout = zipfile.ZipFile(file_path, 'w')
for item, buffer in buffers:
zout.writestr(item, buffer)
zout.close()
workbook.close()

Xref table not zero-indexed. ID numbers for objects will be corrected. won't continue

I am trying to open a pdf to get the number of pages. I am using PyPDF2.
Here is my code:
def pdfPageReader(file_name):
try:
reader = PyPDF2.PdfReader(file_name, strict=True)
number_of_pages = len(reader.pages)
print(f"{file_name} = {number_of_pages}")
return number_of_pages
except:
return "1"
But then i run into this error:
PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]
I tried to use strict=True and strict=False, When it is True, it displays this message, and nothing, I waited for 30minutes, but nothing happened. When it is False, it just display nothing, and that's it, just do nothing, if I press ctrl+c on the terminal (cmd, windows 10) then it cancel that open and continues (I run this in a batch of pdf files). Only 1 in the batch got this problem.
My questions are, how do I fix this, or how do I skip this, or how can I cancel this and move on with the other pdf files?
If somebody had a similar problem and it even crashed the program with this error message
File "C:\Programy\Anaconda3\lib\site-packages\PyPDF2\pdf.py", line 1604, in getObject
% (indirectReference.idnum, indirectReference.generation, idnum, generation))
PyPDF2.utils.PdfReadError: Expected object ID (14 0) does not match actual (13 0); xref table not zero-indexed.
It helped me to add the strict argument equal to False for my pdf reader
pdf_reader = PdfReader(input_file, strict=False)
For anybody else who may be running into this problem, and found that strict=False didn't help, I was able to solve the problem by just re-saving a new copy of the file in Adobe Acrobat Reader. I just opened the PDF file inside an actual copy of Adobe Acrobat Reader (the plain ol' free version on Windows), did a "Save as...", and gave the file a new name. Then I ran my script again using the newly saved copy of my PDF file.
Apparently, the PDF file I was using, which were generated directly from my scanner, were somehow corrupt, even though I could open and view it just fine in Reader. Making a duplicate copy of the file via re-saving in Acrobat Reader somehow seemed to correct whatever was missing.
I had the same problem and looked for a way to skip it. I am not a programmer but looking at the documentation about warnings there is a piece of code that helps you avoid such hindrance.
Although I wouldn't recomend this as a solution, the piece of code that I used for my purpose is (just copied and pasted it from doc on link)
import sys
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
This happens to me when the file was created in a printer / scanner combo that generates PDFs. I could read in the PDF with only a warning though so I read it in, and then rewrote it as a new file. I could append that new one.
from PyPDF2 import PdfMerger, PdfReader, PdfWriter
reader = PdfReader("scanner_generated.pdf", strict=False)
writer = PdfWriter()
for page in reader.pages:
writer.add_page(page)
with open("fixedPDF.pdf", "wb") as fp:
writer.write(fp)
merger = PdfMerger()
merger.append("fixedPDF.pdf")
I had the exact same problem, and the solutions did help but didn't solve the problem completely, at least the one setting strict=False & resaving the document using Acrobat reader.
Anyway, I still got a stream error, but I was able to fix it after using an PDF online repair. I used sejda.com but please be aware that you are uploading your PDF on some website, so make sure there is nothing sensible in there.

python win32 error,Microsoft Excel',

my last part of code is as follows;
from openpyxl import Workbook
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
for wb in excel.Workbooks:
if wb.Name[:10] == 'da_woprint' :
print('yes')
import os
os.chdir('C:\\Users\\maliadil\\Desktop')
wb.SaveAs(r'C:\Users\maliadil\Desktop\{0}.xls'.format(r))
excel.Application.Quit()
browserchr3.quit()
I have automated my chrome to use one of my Maximo web application to do some task and get the daily report which comes out in excel (.xls)format.I was able to do the whole thing,except the last step,which is nothing but saving this excel file,in a directory using a variable "r"(which contain previous day's date in string format),in which I am getting the error.But I am able to save it with a static name`.
Judging from your comment:
What I think you want is that the 5 is replaced with a variable.
In your case you want it to be stored in variable r. (This is not a very good name by the way).
So what you need to do is to inject your variable into your string somehow. There are a couple of ways to do this.
The first way is my favorite:
r = 5
wb.SaveAs('C:\Users\maliadil\Desktop\{0}.xls'.format(r))
You could also use %s to make this case work and a couple of other things, for more info, here
If you want to store the whole string, what you may want to do, I still don't really understand the case, is the following:
r = 'C:\Users\maliadil\Desktop\{0}.xls'.format(5)
wb.SaveAs(r)

Python xlsxwriter Repaired Records: String properties from /xl/sharedStrings.xml part (Strings)

I'm creating and writing into an excel file using xlsxwriter module. But when I open the excel file, I get this popup:
We found a problem with some content in 'excel_sheet.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of this workbook, click Yes. If I click Yes, it says Repaired Records: String properties from /xl/sharedStrings.xml part (Strings) and then I can see the contents.
I found that this occurs because of the cells I wrote using write_rich_string.
my_work_sheet.write_rich_string(row_no, col_no,format_1, "Some text in format 1", format_2, "Text in format 2", format_1, "Again in format 1")
If I write it using write_string this doesn't occur. format_1 and format_2 has font name, color, size and vertical align set.
Can anyone suggest what goes wrong here?
I was trying to recreate(Thanks to #jmcnamara) the problem and I could figure out where it went wrong.
In my command to write_rich_string, sometimes it was trying to format the empty string.
my_work_sheet.write_rich_string(row_no, col_no,format_1, string_1, format_2, string_2, format_1, string_3)
I came to know that at some point of time the value of one among string_1, string_2 and string_3 becomes ''. Now I use write_rich_string only after ensuring they are not ''.
In general that "We found a problem with some content" error/warning from Excel means that an XML element or attribute is malformed in one of the component files in the xlsx file. Again, in general, that means that there is a bug in XlsxWriter or that it has failed to sanitize the user input in some way.
However, in this particular case there isn't enough information to determine what the issue is. I took your snippet of code and turned it into a test program and it works as expected.
import xlsxwriter
workbook = xlsxwriter.Workbook('rich_strings.xlsx')
my_work_sheet = workbook.add_worksheet()
my_work_sheet.set_column('A:A', 50)
format_1 = workbook.add_format({'color': 'red'})
format_2 = workbook.add_format({'color': 'blue'})
my_work_sheet.write_rich_string(0, 0,
format_1, "Some text in format 1 ",
format_2, "Text in format 2 ",
format_1, "Again in format 1")
workbook.close()
Output:
So, you will need to create a small self contained program like the above and submit a bug report to the XlsxWriter project.

Resources