How to save Xlsxwriter file in certain path? - python

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

Related

Excel file can't be opened after saved from Tkinter

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?

Why won't pandas excel writer write to my file path?

I'm trying to output an .xlsx file with pd.ExcelWriter as shown below:
writer_t = pd.ExcelWriter('C:/Users/bbecker021/AppData/Local/Programs/Python/Python38/Project_Catalog_Template_IDs.xlsx', engine='xlsxwriter')`
I then append to the file with:
data_requirements_DF.to_excel(writer_t, sheet_name=repo_list[element])
And print out the dataframe being added:
print("---", repo_list[element], "data_requirements---\n", data_requirements_DF)
But when I check the folder path I specify above, there is no file...any help as to check what might be happening?

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.

Python openpyxl saving xlsm file gets error when opening

I have a script that opens an xlsm file and an xlsx file. It modifies the xlsm with data from the xlsx, then saves the xlsm file. When i open that xlsm file after the script is run, I get an error shown in the image.
The file then works fine but I get an XML error shown below:
The code I am using is:
import openpyxl
destwb = openpyxl.load_workbook(filename="C:\\627 Data\\winphy\\071-000-022-00 627 data.xlsm", read_only=False, keep_vba=True)
.....Code.....
destwb.save(filename="C:\\627 Data\\winphy\\071-000-022-00 627 data2.xlsm")
I ran into something similar and pieced largely recycled code from this solution by Joost in this question: How to save XLSM file with Macro, using openpyxl
Apparently, openpyxl doesn't read or preserve all of the magic macro parts of an xslm when opening and saving. Since the files are in a zip format, the solution:
Saves your work as an xlsx
Opens the original xlsm as a zip and extracts the key parts
Creates a new zip with the data from your saved xlsx and the above key parts
Renames that as a xlsm
I took the sample code, turned it into a usable replacement for workbook.save(), fixed a missing file (likely Excel change since the original solution), added zip compression and creation of a backup file to the mix. May this do what you need.
def saveXlsm(wb, xlsmname):
'''Some crazy workaround to fix what openpyxl cannot when recreating an xlsm file.
Use as replacement for workbook.save()
'''
import zipfile
from shutil import copyfile
from shutil import rmtree
# Unzip original and tmp into separate dirs
PAD = os.getcwd()
wb.save('tmp.xlsx')
with zipfile.ZipFile(xlsmname, 'r') as z:
z.extractall('./xlsm/')
with zipfile.ZipFile('tmp.xlsx', 'r') as z:
z.extractall('./xlsx/')
# copy pertinent left out macro parts into tmp
copyfile('./xlsm/[Content_Types].xml','./xlsx/[Content_Types].xml')
copyfile('./xlsm/xl/_rels/workbook.xml.rels','./xlsx/xl/_rels/workbook.xml.rels')
copyfile('./xlsm/xl/vbaProject.bin','./xlsx/xl/vbaProject.bin')
copyfile('./xlsm/xl/sharedStrings.xml','./xlsx/xl/sharedStrings.xml')
# create a new tmp zip to rebuild the xlsm
z = zipfile.ZipFile('tmp.zip', 'w', zipfile.ZIP_DEFLATED)
# put all the parts back into the new Frankenstein
os.chdir('./xlsx')
for root, dirs, files in os.walk('./'):
for file in files:
z.write(os.path.join(root, file))
z.close()
os.chdir(PAD)
# humanize Frankenstein
bakname = xlsmname + '.bak'
if os.access(bakname, os.W_OK):
os.remove(bakname)
os.rename(xlsmname, bakname)
os.rename('tmp.zip', xlsmname)
#clean
rmtree('./xlsm/')
rmtree('./xlsx/')
os.remove('./tmp.xlsx')

Categories

Resources