Can't save data to file when opening Python script from CMD - python

I have a short script that takes user input and save it to a spreadsheet. When opened from CMD, it seems to run properly, without any errors. However, the data from user input is actually not saved at all.
Here's the code:
import openpyxl
wb = openpyxl.load_workbook('C:\\Users\\sp\\Documents\\testFolder\\testTF.xlsx')
sheet = wb.active
while True:
print('Enter pairs seprated with colon')
pairList = input().split(':')
maxRowNum = sheet.max_row
sheet.cell(row=maxRowNum + 1, column=1).value = pairList[0]
sheet.cell(row=maxRowNum + 1, column=2).value = pairList[1]
wb.save('testTF.xlsx')
print('Pair saved\n\n')
If opened from File Explorer instead of CMD, the script do save data as intended. But in CMD, it doesn't.
Things I've tried to solve the problem:
Run the script in CMD as Admin, instead of normal user
Uncheck the "Read Only" property of the parent folder
Create a new folder and move the script into it.
Uncheck the "Read Only" property of the new parent folder
Run the following CMD commands as Admin: "attrib -r +s C:\Users\sp\Documents\testFolder", or "attrib -r -s C:\Users\sp\Documents\testFolder", according to https://appuals.com/how-to-fix-folder-keeps-reverting-to-read-only-on-windows-10/
None of the upper approaches works. When run in CMD, the script still doesn't save data to spreadsheet. I'm not sure what's wrong and how to solve this. Could anyone help? I really appreciate it.

You are reading from one path and saving in another.
Try:
import openpyxl
wb = openpyxl.load_workbook('C:\\Users\\sp\\Documents\\testFolder\\testTF.xlsx')
sheet = wb.active
while True:
print('Enter pairs seprated with colon')
pairList = input().split(':')
if len(pairList) < 2:
break
maxRowNum = sheet.max_row
sheet.cell(row=maxRowNum + 1, column=1).value = pairList[0]
sheet.cell(row=maxRowNum + 1, column=2).value = pairList[1]
wb.save('C:\\Users\\sp\\Documents\\testFolder\\testTF.xlsx')
print('Pair saved\n\n')
I just test it and works fine. Maybe you have the excel open, and blocking edition?

Related

Running script.exe gives PermissionError: [Errno 13] , but running the same code in script.py doesn't

I have a Python script that modifies an Excel file. It works fine.
When I turn that same script into an executable, and try to run it, it gives me an error saying it can't modify the Excel file.
I don't understand why. I run the .exe as an admin. The Excel file is not read-only and can be modified by admins. Any help would be appreciated.
The line that gives the error is wb.save('mybots.xlsx')
def myClick():
wb = openpyxl.load_workbook(r"mybots.xlsx")
sheet = wb["Sheet1"]
# loop through the list of checkboxes and write their value to excel
idx = 0
while idx < list_length:
cb = list_checkboxes[idx]
varname = cb.cget("variable")
cbValue = root.getvar(varname)
sheet.cell(row=idx+2, column=2).value = str(cbValue)
idx += 1
wb.save('mybots.xlsx')

How do I download an xlsm file and read every sheet in python?

Right now I am doing the following.
import xlrd
resp = requests.get(url, auth=auth).content
output = open(r'temp.xlsx', 'wb')
output.write(resp)
output.close()
xl = xlrd.open_workbook(r'temp.xlsx')
sh = 1
try:
for sheet in xl.sheets():
xls.append(sheet.name)
except:
xls = ['']
It's extracting the sheets but I don't know how to read the file or if saving the file as an .xlsx is actually working for macros. All I know is that the code is not working right now and I need to be able to catch the data that is being generated in a macro. Please help! Thanks.
I highly recommend using xlwings if you want to open, modify, and save .xlsm files without corrupting them. I have tried a ton of different methods (using other modules like openpyxl) and the macros always end up being corrupted.
import xlwings as xw
app = xw.App(visible=False) # IF YOU WANT EXCEL TO RUN IN BACKGROUND
xlwb = xw.Book('PATH\\TO\\FILE.xlsm')
xlws = {}
xlws['ws1'] = xlwb.sheets['Your Worksheet']
print(xlws['ws1'].range('B1').value) # get value
xlws['ws1'].range('B1').value = 'New Value' # change value
yourMacro = xlwb.macro('YourExcelMacro')
yourMacro()
xlwb.save()
xlwb.close()
Edit - I added an option to keep Excel invisible at users request

Python script that creates multiple user accounts from an excel file in Ubuntu

I'm trying to create a Python script that creates user accounts in Ubuntu from an excel file. The excel file contains:
Full name, an username and a password.
This is my code at the moment:
#!/usr/bin/env python
import os
import openpyxl
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
excel_file = os.open("Names_mod.xlsx", os.O_RDONLY)
wb = openpyxl.load_workbook("Names_mod.xlsx")
sheet = wb.active
max_row = sheet.max_row
for i in range(1, max_row + 1):
name = sheet.cell(row = i, column = 1)
addUser = "sudo useradd -m" + "name.value"
os.system(addUser)
At the moment I'm just trying to create the user accounts without the password but I can't get it to work. Now it only creates one account from column 1, row 12 for some reason.
Anyone know what the problem could be? Would appreciate the help :)

How to pass Variable from Python to VBA Sub

I am trying to call a VBA sub from my Python code to convert all excel files in a specified folder from the xls to xlsm format.
I can use the following code when I am not using a variable in the VBA and it works well.
Python Code:
import os
import win32com.client
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal"
xl.Application.Quit() # Comment this out if your excel script closes
del xl
VBA Code:
Public Sub xlstoxlsmFinal()
' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
Path = "C:\Users\Name\Documents\Monthly Reports\16.06 Reports\Agent Reports"
queue.Add fso.GetFolder(Path)
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then
Workbooks.Open Filename:=oFile
ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
End If
Next oFile
Loop
However, I am unable to call the function when I try to pass a variable from python to VBA. Below is what I have tried so far.
Python code with variable:
import os
import win32com.client
Datev = """16.06 """
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal(" + Datev + ")")
## xl.Application.Save() # if you want to save then uncomment this line and change delete the ", ReadOnly=1" part from the open function.
xl.Application.Quit() # Comment this out if your excel script closes
del xl
VBA code with Variable:
Public Sub xlstoxlsmFinal(Datev As String)
' goes through all the sub folders of a specified folder and created an xlsm(macro enabled version) of any xls documents
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
Path = "C:\Users\Name\Documents\Monthly Reports\" & Datev & "Reports\Agent Reports"
queue.Add fso.GetFolder(Path)
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
If Right(oFile, 4) <> "xlsm" And Right(oFile, 3) <> "pdf" Then
Workbooks.Open Filename:=oFile
ActiveWorkbook.SaveAs Filename:=oFile & "m", FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
ActiveWorkbook.Close
End If
Next oFile
Loop
When I run this in python I get the error message:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u"Cannot run the macro 'PERSONAL.XLSB!Module1.xlstoxlsmFinal(16.06 )'. The macro may not be available in this workbook or all macros may be disabled.", u'xlmain11.chm', 0, -2146827284), None)
Would anybody know how to succesfully pass a Python variable to a VBA sub?
Thanks!
Per Tim Williams suggestion I read the last section of rondebruin.nl/win/s9/win001.htm and formulated the python code
import os
import win32com.client
Datev = """16.06 """
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONAL.XLSB", ReadOnly=1)
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal", Datev)
xl.Application.Quit() # Comment this out if your excel script closes
del xl
The material difference was changing the line:
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal(" + Datev + ")")
To:
xl.Application.Run("PERSONAL.XLSB!Module1.xlstoxlsmFinal", Datev)
Now the code works perfectly!
Go to Macro Security under the developer tag and choose the Enable all macros option

Saving excel work book not working in python

for sheet_name in book.sheet_names():
for index in range(len(tabs)):
tab = tabs[index]
if sheet_name == tab:
dump_file_name = dump_files[index]
dump_file_name = file_prefix+dump_file_name
sheet = book.sheet_by_name(sheet_name)
new_book = Workbook()
sheet1 = new_book.add_sheet("Sheet 1")
for row in range(sheet.nrows):
values = []
for col in range(sheet.ncols):
sheet1.write(row,col,sheet.cell(row,col).value)
xlsx_file_name = dirname+"/"+dump_file_name+".xlsx"
sheet1.title = xlsx_file_name
new_book.save(xlsx_file_name)
The file is creating and data is there, but if I open it in openoffice.org and click the save button it asks for new name.
The file can not be read by PHP also. Again if I open and save it with new name then it works perfectly. I think we have to add something in the code so that it could be used by PHP.
i did google and found the solution here
http://xlsxwriter.readthedocs.org/getting_started.html
This is exactly what i wanted.
Creating and saving files to xlsx format.
Now its working perfectly.
original source
How to save Xlsxwriter file in certain path?
important link:
https://pypi.python.org/pypi/PyExcelerate

Categories