I want to add VBA project to my excel file I'm creating using 'xlsxwriter' library. In their example https://xlsxwriter.readthedocs.io/working_with_macros.html they extract vba project from another excel file and add it to the current. I want to add an already existing .bin file to my excel file. The problem is that excel removes this file. Here is my python code
from xlsxwriter import *
import os
workbook = Workbook('ShipBattle.xlsm')
menuws = workbook.add_worksheet('Menu')
gamews = workbook.add_worksheet('Game')
workbook.set_vba_name('MyWorkbook')
menuws.set_vba_name('Sheet1')
gamews.set_vba_name('Sheet2')
workbook.add_vba_project('vbaProject.bin')
gamews.insert_button('F10', {'macro' : 'Test', 'caption' : 'End Turn', 'width' : 80, 'height' : 30})
workbook.close()
and here is my vba code from .bin file
Sub Test()
MsgBox "Hello, world!"
End Sub
Here is the window:
pic of removing my vbaProject.bin
Related
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
I would like to convert a folder full of TDMS files 1:1 to XLSX.
Since important is that the Excel file has the same tabs as the TDMS file and the same file name.
I get the tabs read and the file names, but I don't know how to create new Excel files with the same names and content as the TDMS. Thats what i have tried so far:
from nptdms import TdmsFile
from nptdms import tdms
import os,glob
#Namen aller TDMS-Dateien in einem Ordner
file_names=glob.glob('*.tdms')
for file in glob.glob("*.tdms"):
tdms_file = TdmsFile.read(file)
tdms_groups = tdms_file.groups()
print(tdms_groups)
Now i found out, how to save each TDMS-File as XLSX,
import os, xlsxwriter,glob
import numpy as np
import pandas as pd
from nptdms import TdmsFile
from nptdms import tdms
file_names=glob.glob('*.tdms')
# Read the files back into a dataframe
dataframe_list = []
for file in glob.glob("*.tdms"):
tdms_file = TdmsFile.read(file)
df = tdms_file['Line 1'].as_dataframe()
dataframe_list.append(df)
file = file.replace(".tdms", "")
df.to_excel(str(file)+".xlsx")
But the problem is i have to know the path name ( Line 1 in this case).
I want to find out the path or group names, to save the XLSX File with alle tabs and the same name as in the original TDMS-File.
So can someone tell me how to read the individual tab names before opening the file and then create an XLSX file with the same number of tabs, the same tab name and content?
Edit:
When i use the command tdms_file.groups() i´ll get the following output:
[<TdmsGroup with path /'Line 1'>, <TdmsGroup with path /'Current_Line 1'>]
, but i can´t just get the tab names only ( "Line 1" and "Current Line 1"). After that i want to create an XLSX-File with the tab "Line 1" and the tab "Current Line 1" with the same content.
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)
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
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