run macro in xlsm using python - python

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

Related

Error open file after saving it with storeFile of pysmb

I am reading an Excel file (.xlsx) with pysmb.
import tempfile
from smb.SMBConnection import SMBConnection
conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
conn.connect(server_ip, 139)
file_obj = tempfile.TemporaryFile()
file_attributes, filesize = conn.retrieveFile(service_name, test.xlsx, file_obj)
This step works, I am able to transform the file in pandas.DataFrame
import pandas as pd
pd.read_excel(file_obj)
Next, I want to save the file, the file is saved but if I want to open it with Excel, I have an error message "Excel has run into an error"
Here the code to save the file
conn.storeFile(service_name, 'test_save.xlsx', file_obj)
file_obj.close()
How can I save correctly the file and open it with excel ?
Thank you
I tried with a .txt file file and it is working. An error occurs with .xlsx, .xls and .pdf files. I have also tried without extension, same issue, imossible to open the file.
I would like to save the file with .pdf and .xlsx extension, and open it.
Thank you.
I found a solution an I will post it here in case someone face a similar issue.
Excel can be save as a binary stream.
from io import BytesIO
df = pd.read_excel(file_obj)
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, sheet_name='data', index = False)
writer.save()
output.seek(0)
conn.storeFile(service_name, 'test_save.xlsx', output)

How to save a a new excel file in Python

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")

Python - VBA Improvement

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

Print Excel to pdf with xlwings

I am trying to print Excel files to pdf with xlwings. I am using the excel api for this.
I have tried it in two ways:
1/ Using the PrintOut() call with PrintToFile argument:
wb.api.PrintOut(PrintToFile=True, PrToFileName="5.pdf", Preview=True)
The problem here is Excel just prints the file, ignoring my additional settings.
2/ Using ExportAsFixedFormat
wb.api.ExportAsFixedFormat(0, str(SwmId) + ".pdf")
Here Excel flashes a bit, but does not do anything in the end.
For the record: I can't use a macro and call it from Python because I have about a thousand of these Excel files. So, I can't put the macro in every single one of them. It would probably be a workaround to create a custom function in VBA and than call it every file. But, honestly, it would be easier if I could just do this directly from Python, in one line of code.
Below is a self-standing code example of what worked on my machine to print an excel workbook to pdf (using the ExportAsFixedFormat method):
# Environment
# -----------
# OS: Windows 10
# Excel: 2013
# python: 3.7.4
# xlwings: 0.15.8
import os
import xlwings as xw
# Initialize new excel workbook
book = xw.Book()
sheet = book.sheets[0]
sheet.range("A1").value = "dolphins"
# Construct path for pdf file
current_work_dir = os.getcwd()
pdf_path = os.path.join(current_work_dir, "workbook_printout.pdf")
# Save excel workbook to pdf file
print(f"Saving workbook as '{pdf_path}' ...")
book.api.ExportAsFixedFormat(0, pdf_path)
# Open the created pdf file
print(f"Opening pdf file with default application ...")
os.startfile(pdf_path)
xlwings documentation recommends using xw.App():
from pathlib import Path
import xlwings as xw
import os
with xw.App() as app:
# user will not even see the excel opening up
app.visible = False
book = app.books.open(path_to_excelfile)
sheet = book.sheets[0]
sheet.page_setup.print_area = '$A$1:$Q$66'
sheet.range("A1").value = "experimental"
# Construct path for pdf file
current_work_dir = os.getcwd()
pdf_file_name = "pdf_workbook_printout.pdf"
pdf_path = Path(current_work_dir, pdf_file_name)
# Save excel workbook as pdf and showing it
sheet.to_pdf(path=pdf_path, show=True)

How to write in to already opened excel file by using openpyxl

I opened a excel file by using the following code:
from openpyxl import load_workbook
wb = load_workbook('path of the file')
DriverTableSheet = wb.get_sheet_by_name(name = 'name of the sheet')
after that I have to append some values in that excel file..
for that I used the following code
DriverTableSheet.cell(row=1, column=2).value="value"
But it is not responding. Can u guys please guide how to write / append a data in that excel file and save that excel file

Categories

Resources