Excel file can't be opened after saved from Tkinter - python

I am using xlsxwriter library to write data in excel file and it works fine, when excel file is saved in root directory.
I want to enable user to choose where to save the file, so I am using from asksaveasfile from tkinter.filedialog :
files = [('Excel Document', '.xlsx'), ('All Files', '*.*')]
workbook = asksaveasfile(filetypes=files, defaultextension=files)
The file saves in specified folder, but won't open:
Excel cannot open the file
I also tried .xls , again, file can't be opened.
Thank you in advance!

Your code is not complete and can not be fixed if you do not include the saving part (what happens to workbook after user choose file to save?).
It seems you are writing an empty file. Check if it has 0 size or not?

Related

Python Tkinter browse for excel file, save one sheet from wb to csv without opening

new to python and coding in general. I have a GUI that allows the user to browse to an excel file, open it, read it, and renames to a new directory. The process opens the excel file.
Two issues- 1. It takes a while for the excel file to open because of add-in's, etc. Is there a way to bypass the actual opening of the file?
2. The df.to_excel doesn't happen happen in the GUI until the opened excel file is manually closed.
Any help would be appreciated. Thanks!
import tkinter as tk
from tkinter import filedialog
import pandas as pd
import os
window = tk.Tk()
def openFile():
filename = filedialog.askopenfilename(initialdir = r'L:\My directory',
filetypes=[("Excel Files", "*.xlsx")])
os.system(filename)
df = pd.read_excel(filename, sheet_name = 'Order Details')
df.to_excel(r'C:/Users/Name/AppData/Local/Programs/Python/Project/DQ_File/scan.xlsx',index=False)
button = tk.Button(frame, text='Import Intelliscan File', bg='aliceblue', fg='black',command=openFile)
button.place(relx=0.03, rely=0.02, relheight=0.16, relwidth=0.95)
The os.system call blocks until the program it has started is finished. That is working as intended.
So that is why the conversion only happens after you close excel.
(If you want to open an excel file in excel without blocking, use subprocess.Popen.)
If you just want to rename a file, use shutil.move.

xlwings open workbook using context manager and overwrite it after making changes

What I want to do is to open csv file, make changes inside and save it. My code looks like this:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath, FileFormat=FileFormat.xlCSV)
This code kinda works but when it saves the file it asks me if i want to overwrite the file since it already exists.
So what I did was to save it as "csv.txt" file, then remove the ".csv" file and rename ".csv.txt" file back to ".csv" file using code below:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath + '.txt', FileFormat=FileFormat.xlCSV)
os.remove(savePath)
os.rename(savePath + '.txt', savePath)
Issue I have here is that I get error:
"PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:"
Which means that Python tries to rename files while its being saved.
So my questions are:
Is there a way to overwrite csv file without needing to manually click "file already exists - do You want ot ovewrite it" prompt ?
Is there anything I can change in my code to not get [WinError 32] shown above ?
How can I change my code to not open two instances of excel (now it opens blank one - probably when I use "with" statement and second one with my file when I use app.books.open) ?
Thank You in advance for any kind of help.
I had the same problem caused by corrputed excel file saved by Excel Writer.
If you are writing an excel file in previous lines with pd.ExcelWriter and later you use the same file for xlwings, use context manager for Writer.
You don't have to overwrite the file by xlwings, you can simple do: wb.save(path=None). It will save the same file under the same name.
Just be attentive on the file you re using if it is a healty excel file - I mean not corrupted.

VBA script to trigger Python and saving down xlsx file

I am trying to save the .xlsx file and using VBA as a wrapper to execute the python file. However, I can validate that python code runs, but somehow .xlsx file is not saved. When I run the same python file via IDE, it saves down the .xlsx file.
VBA code
Sub RunPython()
Dim shell As Object
Dim exepath, scriptPath As String
Set Shell = VBA.CreateObject("Wscript.Shell")
exePath = """C:\Program Files\...\python.exe"""
scriptPath = "C:\....\mymodule.py"
Python Script
import pandas as pd
import xlsxwriter
df = pd.DataFrame(np.random.randn(5,2),index=range(0,10,2),columns =list('AB'))
excel_file ='sample.xlsx'
writer = pd.ExcelWriter(excel_file,engine='xlsxwriter')
df.to_excel(writer,sheet_name='Data')
print ("file read")
writer.save()
writer.close()
Does that 'excel_file' have a path?
Does Python use a current directory and automatically add it to Excel file name?
If yes, do you know how to obtain it and can you look for .xlsx file there?
If not, how do you check if the .xlsx file has been saved? Where are you looking for?
Does Python raise any error?
I am looking to the code mostly like a VBA user...
I would suggest to send a message from Python, containing the current directory path. Supposing that the .xlsx workbook path has not somehow been defined and the code presented here does not include that part. Theoretically it should use the same current directory, but I think it is good to be checked...

Run Excel VBA code from newly created Excel file using Python

I am trying to run Excel macros from ABAQUS software tool which has inbuilt Python.
I have a default Excel file, I want this as a main Excel file and to make a new Excel file depending on the output database file.
I access the ABAQUS output data base file and get its name and make a new Excel file named by combining the output data base file name plus some other name.
I copy the main Excel file to this new Excel file.
I am able to open this newly created file, but I am unable to run the macros.
Here is the code with comments.
I get the path of my file with name and extension
filePath = odbFile.path
Filename with extension only
filename_w_ext = os.path.basename(filePath)
odbfilename,odbfileExtension = os.path.splitext(filename_w_ext)
excel_filename='abc.xlsm'
odbfilename+'_FAT'+'.xlsm'
newExcelFile = odbfilename+'_FAT'+'.xlsm'
shutil.copy(excel_filename, newExcelFile)
I access the win32client to access the Excel application
xl = win32com.client.Dispatch("Excel.Application")
Opening the Excel file, give the file path
xl.Workbooks.Open(newExcelFile)
Say newExcelFile created name is new.xlsm.
To run the Excel macros using PYTHON, the default code is
xl.Application.Run("excelName!ModuleNumberOfTheMacro.MacroName")
Run my macro to import nodes from Excel
xl.Application.Run("newExcelFile!Module1.ImporterFichiersTextes")
I put down the same format but Python is looking for the Excel sheet 'newExcelFile', instead of new.xlsm.

How to save Xlsxwriter file in certain path?

Where does Xlsxwriter save the files you have created? Is it possibly to specify the path where I want the excel files to be saved?
My XlsxWriter script was in file /app/smth1/smth2/ and for some reason it saved the excel file to /app/. Shouldn't it have saved it in the same file where the script was? Or do I have to specify the path like this:
workbook = xlsxwriter.Workbook(' /app/smth1/smth2/Expenses01.xlsx')
What is the default file where the excel file is saved?
Here's how you can save the file to the current directory (where your script is running from):
workbook = xlsxwriter.Workbook('demo.xlsx')
Here's how you can specify a full path:
workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
Here's how you can specify a relative path:
workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
Note that a starting "/" is not needed and may cause errors.
More examples can be found here

Categories

Resources