I have a pandas dataframe df. I then save it as an excel file Report.xlsm and then I add VBA code to filter this data.
The code runs well. However, when I execute the VBA code, Excel always shows the message box to ask to save the Report.xlsm. Does anyone know how to get rid of this message and automatically save it, rahter than having to click save?
If I do not click save, the excel file will be broken and the code will be crash too.
Microsoft Excel, ask to save file notification
Python Code:
desktop = os.path.normpath(os.path.expanduser("~/Desktop"))
# Generate excel file
writer = pd.ExcelWriter(desktop + '\Report.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index = False, sheet_name = 'Report')
workbook = writer.book
workbook.filename = desktop + '\Report.xlsm'
# Add VBA code to new excel report - Report.xlmx from vbaProject.bin
workbook.add_vba_project('vbaProject.bin')
writer.save()
# RUN MACRO
exel = win32com.client.Dispatch('Excel.Application')
exel.Workbooks.Open(Filename = desktop + '\Report.xlsm' , ReadOnly=1)
xl.Application.Run("Macro1")
xl.Application.Quit()
del xl
Add this at the end of your code
exel.ActiveWorkbook.Close(True)
True = Save,
False = Do Not Save
Related
Open excel,then click file->New->Blank workbook, we can get a blank workbook. We can input some information.
I want to use Python to save the created Excel to the path we set.
import win32com.client
import os
excel = win32com.client.Dispatch("Excel.Application")
xlsx_fullname = os.path.abspath("Book1")
workBook = excel.Workbooks.Open(xlsx_fullname)
excel.ExecuteExcel4Macro("FDSFORCERECALC(False)")
workBook.Save()
workBook.Close(True)
excel.Application.Quit()
I used this code, but I can't use python to select this excel file. It's not working
Change
xlsx_fullname = os.path.abspath("Book1")
workBook = excel.Workbooks.Open(xlsx_fullname)
...
workBook.Save()
to
workBook = excel.ActiveWorkbook
...
workBook.SaveAs(Filename="c:/path/to/your desired filename.xlsx")
When running my code with a macro workbook, I get the following error: "Excel cannot be open the file 'filename.xlsm' because the file format or file extension is not valid," but when I run my code on an xlsx file, I do not get this error and the new workbook loads up fine.
I am using Pandas to read the file with the openpyxl engine. I've tried solutions with the XlsxWriter, and that hasn't helped.
Appreciate any suggestions
This is how I write to a new workbook:
writer = pd.ExcelWriter(file_path2, engine = 'openpyxl', mode = 'a', if_sheet_exists = 'replace') #Append data to exisiting sheet
dataClean.to_excel(writer, sheet_name = 'Data Input', header = False, index = False)
writer.save()
writer.close()
I know this is an old post, but recently I have ran into the same issue and this was the only post I've found about it.
writer.close() already saves the file according to the documentation. There is no need to call writer.save() manually.
You could also use a with statement:
with pd.ExcelWriter(file_path2, engine = 'openpyxl', mode = 'a', if_sheet_exists = 'replace') as writer: # Append data to exisiting sheet
dataClean.to_excel(writer, sheet_name = 'Data Input', header = False, index = False)
I'm making a Python program that opens, edits, and saves xlsm Excel files with VBA. However, in this line wb.save(filename = 'b.xlsm'), the following error is occurring: lxml.etree.XMLSyntaxError: Opening and ending tag mismatch: br line 19 and b, line 20, column 12.
I must edit and save the xlsm file.
import openpyxl
wb = openpyxl.load_workbook(filename = 'a.xlsm', keep_vba = True)
ws = wb.active
ws.cell(1,1).value = 'test'
print(ws.cell(1,1).value)
wb.save(filename = 'b.xlsm')
Gonna guess something is broken in another part of your code, as this aren't 20 lines and the code on itself runs just fine on my machine :) Based on the error code, you are just missing a bracket somewhere
After I run the code, I cannot seem to open the generated excel file, because my computer says it is "open in another program". If I close python, then I can open it.
When I try to add "workbook.close()" to the code, I get the error "Calling close() on already closed file." So it seems python already closed it.
What can I do to be able to see my outputs without having to close python?
import pandas as pd
# Import data
df = pd.read_excel (r'C:\Users\Desktop\work\charts\constraints.xlsx' , sheet_name='biggestobstacle')
print (df)
# File 2 is the new excel table with the chart. Hence, we keep the originals untouched. We create a new excel + chart.
writer = pd.ExcelWriter("file2.xlsx", engine="xlsxwriter")
df.to_excel(writer, sheet_name='biggestobstacle')
# Get xlsxwriter objects
workbook = writer.book
worksheet = writer.sheets['biggestobstacle']
# Create a 'column' chart
chart = workbook.add_chart({'type': 'column'})
# select the values of the series and set a name for the series
chart.add_series({
'values': '=\'biggestobstacle\'!$B$2:$B$8',
"name": "My Series's Name"
})
# Insert the chart into the worksheet in the D2 cell
worksheet.insert_chart('D2', chart)
writer.save()
# This last line generates an error.
workbook.close()
From:
https://github.com/pandas-dev/pandas/blob/v1.2.3/pandas/io/excel/_base.py#L584-L900
It looks like you just .close() and don't worry about the save()
From the excelWriter class
def close(self):
"""synonym for save, to make it more file-like"""
content = self.save()
self.handles.close()
return content
try using a context manager it handles closing files automatically
it goes like this.
with open("StockQuotes.csv") as csvfile:
dialect = csv.Sniffer().sniff(csvfile.read(1024))
csvfile.seek(0)
hasHeader = csv.Sniffer().has_header(csvfile.read(1024))
csvfile.seek(0)
print("Headers found: " + str(hasHeader))
print(dialect.delimiter)
print(dialect.escapechar)
print(dialect.quotechar)
I have a basic requirement.
I have a .csv file and a .xlsm file which has a macro. I need to copy the .csv file's contents to that .xlsm file and run the macro. I need to use Python.
Is there any script possible to accomplish this?
Thanks in advance.
file_dir = os.path.dirname(import_file_path)
filename = 'sample.xlsx'
writer = pd.ExcelWriter(filename, engine='xlsxwriter')#Write excel file after write data.(only for write temporary data.)
df.to_excel(writer, sheet_name='ResultSet', index=False)
# ATTACH MACRO AND CREATE .XLSM FILE#
filename_macro = 'sample.xlsm'#Create Macro File.
workbook = writer.book
workbook.filename = filename_macro
workbook.add_vba_project('vbaProject.bin')
writer.save()
if os.path.exists("sample.xlsm"):#Check file
xl = win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(os.path.abspath("sample.xlsm"))
xl.Application.Quit() # Comment this out if your excel script closes
del xl
if os.path.exists( 'ResultSet1.xlsx'):#checked file exit or not
# Make duplicate file in user selected directory
xl1 = load_workbook(filename= 'ResultSet1.xlsx')
xl1.save('ResultSet.xlsx')
this link should help to open XLSM via python an fill it with data...
Python, Excel, and Charts using win32com
this one shows you how to run a macro
Python - run Excel macro