Python openpyxl How to bypass permissions to write to an open file - python

I am trying to write a script that live edits an open excel file, but when I try to run the script that uses openpyxl and reads from a cell then writes data back to that cell with an edit, it gives this error PermissionError: [Errno 13] Permission denied: 'GameExcel.xlsx' is there a way around this using another module, or is there a secret I am missing
Edit here's the code, also this is just me learning before I integrate it into the full code.
import openpyxl
from openpyxl import load_workbook
from openpyxl import workbook
from openpyxl.utils import get_column_letter
import os
import tkinter as tk
from tkinter import messagebox as tkMsgBox
import time
os.chdir("D:\Scripts\Python\Testing Scripts\My Excel Game")
wb = load_workbook("GameExcel.xlsx")
names = wb.sheetnames
sheet = wb['GameEnviroment']
#userInput = (input("what would you like it to say?"))
#print(userInput)
C3Val = sheet['C4'].value
sheet.cell(row=3, column=4).value = (C3Val + ' 4')
wb.save('GameExcel.xlsx')
print(C3Val + ' 3')
#sheet['A1']=userInput

This is due to the operating system limitation (ie Windows). It has nothing to do with openpyxl, Python or even Excel. POSIX based OS do not have such a limitation.
The answer to this question ("How to bypass permissions to write to an open file") is simply "You can't".

The option that I went with, and this only works with excel open, is xlwings

Related

Python stream data into an opened excel file

I'm trying stream data from Python to an opened excel file. I've been using openpyxl to do this. Here's the code that I've so far,
from openpyxl import load_workbook
wb = load_workbook('some_data.xlsx')
ws = wb['MySheet']
while True:
current_val = some_method_that_gives_data()
ws['A1'].value = current_val
wb.save('some_data.xlsx')
The functionality I'm trying to achieve is to be able to update the excel data in realtime from Python. The problem is updating data this way gives permission error if the file is already open in MS-Excel (but I want to be able to update it while being open in other apps).
I guess this has more to do with file handling at the OS level, but I'm not able to figure out the solution for this issue.

Openpyxl Reading Non-empty Cells as None [duplicate]

I have a simple excel file:
A1 = 200
A2 = 300
A3 = =SUM(A1:A2)
this file works in excel and shows proper value for SUM, but while using openpyxl module for python I cannot get value in data_only=True mode
Python code from shell:
wb = openpyxl.load_workbook('writeFormula.xlsx', data_only = True)
sheet = wb.active
sheet['A3']
<Cell Sheet.A3> # python response
print(sheet['A3'].value)
None # python response
while:
wb2 = openpyxl.load_workbook('writeFormula.xlsx')
sheet2 = wb2.active
sheet2['A3'].value
'=SUM(A1:A2)' # python response
Any suggestions what am I doing wrong?
It depends upon the provenance of the file. data_only=True depends upon the value of the formula being cached by an application like Excel. If, however, the file was created by openpyxl or a similar library, then it's probable that the formula was never evaluated and, thus, no cached value is available and openpyxl will report None as the value.
I have replicated the issue with Openpyxl and Python.
I am currently using openpyxl version 2.6.3 and Python 3.7.4. Also I am assuming that you are trying to complete an exercise from ATBSWP by Al Sweigart.
I tried and tested Charlie Clark's answer, considering that Excel may indeed cache values. I opened the spreadsheet in Excel, copied and pasted the formula into the same exact cell, and finally saved the workbook. Upon reopening the workbook in Python with Openpyxl with the data_only=True option, and reading the value of this cell, I saw the proper value, 500, instead of the wrong value, the None type.
I hope this helps.
I had the same issue. This may not be the most elegant solution, but this is what worked for me:
import xlwings
from openpyxl import load_workbook
excel_app = xlwings.App(visible=False)
excel_book = excel_app.books.open('writeFormula.xlsx')
excel_book.save()
excel_book.close()
excel_app.quit()
workbook = load_workbook(filename='writeFormula.xlsx', data_only=True)
I have suggestion to this problem. Convert xlsx file to csv :).
You will still have the original xlsx file. The conversion is done by libreoffice (it is that subprocess.call() line).You can use also Pandas for this as a more pythonic way.
from subprocess import call
from openpyxl import load_workbook
from csv import reader
filename="test"
wb = load_workbook(filename+".xlsx")
spread_range = wb['Sheet1']
#what ever function there is in A1 cell to be evaluated
print(spread_range.cell(row=1,column=1).value)
wb.close()
#this line can be done with subprocess or os.system()
#libreoffice --headless --convert-to csv $filename --outdir $outdir
call("libreoffice --headless --convert-to csv "+filename+".xlsx", shell=True)
with open(filename+".csv", newline='') as f:
reader = reader(f)
data = list(reader)
print(data[0][0])
or
# importing pandas as pd
import pandas as pd
# read an excel file and convert
# into a dataframe object
df = pd.DataFrame(pd.read_excel("Test.xlsx"))
# show the dataframe
df
I hope this helps somebody :-)
Yes, #Beno is right. If you want to edit the file without touching it, you can make a little "robot" that edits your excel file.
WARNING: This is a recursive way to edit the excel file. These libraries are depend on your machine, make sure you set time.sleep properly before continuing the rest of the code.
For instance, I use time.sleep, subprocess.Popen, and pywinauto.keyboard.send_keys, just add random character to any cell that you set, then save it. Then the data_only=True is working perfectly.
for more info about pywinauto.keyboard: pywinauto.keyboard
# import these stuff
import subprocess
from pywinauto.keyboard import send_keys
import time
import pygetwindow as gw
import pywinauto
excel_path = r"C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
excel_file_path = r"D:\test.xlsx"
def focus_to_window(window_title=None): # function to focus to window. https://stackoverflow.com/a/65623513/8903813
window = gw.getWindowsWithTitle(window_title)[0]
if not window.isActive:
pywinauto.application.Application().connect(handle=window._hWnd).top_window().set_focus()
subprocess.Popen([excel_path, excel_file_path])
time.sleep(1.5) # wait excel to open. Depends on your machine, set it propoerly
focus_to_window("Excel") # focus to that opened file
send_keys('%{F3}') # excel's name box | ALT+F3
send_keys('AA1{ENTER}') # whatever cell do you want to insert somthing | Type 'AA1' then press Enter
send_keys('Stackoverflow.com') # put whatever you want | Type 'Stackoverflow.com'
send_keys('^s') # save | CTRL+S
send_keys('%{F4}') # exit | ALT+F4
print("Done")
Sorry for my bad english.
As others already mentioned, Openpyxl only reads cashed formula value in data_only mode. I have used PyWin32 to open and save each XLSX file before it's processed by Openpyxl to read the formulas result value. This works for me well, as I don't process large files. This solution will work only if you have MS Excel installed on your PC.
import os
import win32com.client
from openpyxl import load_workbook
# Opening and saving XLSX file, so results for each stored formula can be evaluated and cashed so OpenPyXL can read them.
excel_file = os.path.join(path, file)
excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
excel.DisplayAlerts = False # disabling prompts to overwrite existing file
excel.Workbooks.Open(excel_file )
excel.ActiveWorkbook.SaveAs(excel_file, FileFormat=51, ConflictResolution=2)
excel.DisplayAlerts = True # enabling prompts
excel.ActiveWorkbook.Close()
wb = load_workbook(excel_file)
# read your formula values with openpyxl and do other stuff here
I ran into the same issue. After reading through this thread I managed to fix it by simply opening the excel file, making a change then saving the file again. What a weird issue.

Can't load workbook to openpyxl

I have file path problem when loading an Excel file using openpyxl.
>>>openpyxl.__version__
'2.5.12'
>>>jupyter.__version__
'5.7.4'
import os
import openpyxl
from openpyxl import Workbook
from openpyxl import load_workbook
from openpyxl.reader.excel import load_workbook
>>>os.getcwd()
'/Users/barbara/Documents/17_BMO'
path = "Users/barbara/Documents/17_BMO/Region.xlsx"
wb1 = openpyxl.load_workbook(path)
Instead of loading the workbook, I instead receive the error message:
FileNotFoundError: [Errno 2] No such file or directory: 'Users/barbara/Documents/17_BMO/Region.xlsx'
I fixed it.
I have two same excel files saved in Desktop and Documents. I firstly pointed workbook's path to Desktop, somehow, I can't load excel in Python, then I changed the path to Documents, it didn't work neither. Later on, I changed back to Desktop as my path, it worked. Don't why.

Write data into existing excel file and making summary table

I have to write some data into existing xls file.(i should say that im working on unix and couldnt use windows)
I prefer work with python and have tried some libraries like xlwt, openpyxl, xlutils.
Its not working, cause there is some filter in my xls file. After rewriting this file filter is dissapearing. But i still need this filter.
Could some one tell me about options that i have.
help, please!
Example:
from xlutils.copy import copy
from xlrd import open_workbook
from xlwt import easyxf
start_row=0
rb=open_workbook('file.xls')
r_sheet=rb.sheet_by_index(1)
wb=copy(rb)
w_sheet=wb.get_sheet(1)
for row_index in range(start_row, r_sheet.nrows):
row=r_sheet.row_values(row_index)
call_index=0
for c_el in row:
value=r_sheet.cell(row_index, call_index).value
w_sheet.write(row_index, call_index, value)
call_index+=1
wb.save('file.out.xls');
I also tried:
import xlrd
from openpyxl import Workbook
import unicodedata
rb=xlrd.open_workbook('file.xls')
sheet=rb.sheet_by_index(0)
wb=Workbook()
ws1=wb.create_sheet("Results", 0)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws1.append(arr)
ws2=wb.create_sheet("Common", 1)
sheet=rb.sheet_by_index(1)
for rownum in range(sheet.nrows):
row=sheet.row_values(rownum)
arr=[]
for c_el in row:
arr.append(c_el)
ws2.append(arr)
ws2.auto_filter.ref=["A1:A15", "B1:B15"]
#ws['A1']=42
#ws.append([1,2,3])
wb.save('sample.xls')
The problem is still exist. Ok, ill try to find machine running on windows, but i have to admit something else:
There is some rows like this:
enter image description here
Ive understood what i was doing wrong, but i still need help.
First of all, i have one sheet that contains some values
Second sheet contains summary table!!!
If i try to copy this worksheet it did wrong.
So, the question is : how could i make summary table from first sheet?
Suppose your existing excel file has two columns (date and number).
This is how you will append additional rows using openpyxl.
import openpyxl
import datetime
wb = openpyxl.load_workbook('existing_data_file.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')
a = sheet.get_highest_row()
sheet.cell(row=a,column=0).value=datetime.date.today()
sheet.cell(row=a,column=1).value=30378
wb.save('existing_data_file.xlsx')
If you are on Windows, I would suggest you take a look at using the win32com.client approach. This allows you to interact with your spreadsheet using Excel itself. This will ensure that any existing filters, images, tables, macros etc should be preserved.
The following example opens an XLS file adds one entry and saves the whole workbook as a different XLS formatted file:
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(r'input.xls')
ws = wb.Worksheets(1)
# Write a value at A1
ws.Range("A1").Value = "Hello World"
excel.DisplayAlerts = False # Allow file overwrite
wb.SaveAs(r'sample.xls', FileFormat=56)
excel.Application.Quit()
Note, make sure you add full paths to your input and output files.

Copy Image from Excel and Save it using python

I am trying to copy an image from an excel named Inputs_v3 and sheet named Inputs and save. The code is as follows`
import win32com.client as win32
from PIL import ImageGrab
from xlrd import open_workbook
import os
excel = win32.gencache.EnsureDispatch("Excel.Application")
wb = open_workbook('Inputs_v3.xlsm')
r = wb.sheet_by_name('Inputs')
r.CopyPicture()
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
` The error is as follows
'Attribute error: 'Sheet' object has no attribute 'CopyPicture''
Please suggest where I am doing wrong.Thanks in advance
Use a python library called excel2img. In one line you can take a screenshot from any excel file
import excel2img
excel2img.export_img("Excel File Full Path", "Target Image full Path", "Excel SheetName", None)
and you can identify a specific cells range as well.
import excel2img
excel2img.export_img("test.xlsx", "test.bmp", "", "Sheet2!B2:C15")
I hope this will help.
The following code will get you the win32com reference that you actually need to access the Excel worksheet's objects and methods:
import win32com.client as win32
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open('myworkbook.xlsx')
ws = wb.Worksheets('worksheet_name') # alternatively Worksheets(1) etc
Now you can do, for example:
ws.Shapes(1).CopyPicture()
I've tested this with Python 3.4, pywin32 219 and Excel 2010 on Windows 7.
Note that this doesn't involve xlrd at all - that's a package that can read Excel files without having Excel installed on the computer, but I don't know if it supports getting images of or from Excel workbooks.

Categories