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")
Related
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 roughly 30 excel workbooks I need to combine into one. Each workbook has a variable number of sheets but the sheet I need to combine from each workbook is called "Output" and the format of the columns in this sheet is consistent.
I need to import the Output sheet from the first file, then append the remaining files and ignore the header row.
I have tried to do this using glob/pandas to no avail.
You could use openpyxl. Here's a sketch of the code:
from openpyxl import load_workbook
compiled_wb = load_workbook(filename = 'yourfile1.xlsx')
compiled_ws = compiled['Output']
for i in range(1, 30):
wb = load_workbook(filename = 'yourfile{}.xlsx'.format(i))
ws = wb['Output']
compiled_ws.append(ws.rows()[1:]) # ignore row 0
compiled_wb.save('compiled.xlsx')
Method shown by Clinton c. Brownley in Foundations for Analytics with Python:
execute in shell indicating the path to the folder with excel files ( make sure the argument defining all_workbooks is correct) and then followed by the excel output file as follows:
python script.py <the /path/ to/ excel folder/> < your/ final/output.xlsx>
script.py:
import pandas as pd
import sys
import os
import glob
input_path = sys.argv[1]
output_file = sys.argv[2]
all_workbooks = glob.glob(os.path.join(input_file, '*.xlsx'))
all_df = []
for workbook in all_workbooks:
all_worksheets = pd.read_excel(workbook, sheetname='Output', index_col=None)
for worksheet, data in all_worksheets.items:
all_df.append(data)
data_concatenated = pd.concat(all_df, axis=0, ignore_index=True)
writer = pd.ExcelWriter(output_file)
data_concatenated.to_excel(writer, sheetname='concatenated_Output', index=False)
writer.save()
This will probably get down-voted because this isn't a Python answer, but honestly, I wouldn't use Python for this kind of task. I think you are far better off installing the AddIn below, and using that for the job.
https://www.rondebruin.nl/win/addins/rdbmerge.htm
Click 'Merge all files from the folder in the Files location selection' and click 'Use a Worksheet name' = 'Output', and finally, I think you want 'First cell'. Good luck!
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
I am using WIN32com to use excel. I need to make sure that excel opens up new instances everytime. So if I run this and already have excel open I need it to open a new excel, and with in the script I need it to open a 2nd excel window for file 2 . This is what I am using: I can get it to open but not in new instances.
import win32com.client
import os
x1 = win32com.client.Dispatch("Excel.Application")
wb1= x1.workbooks.Open("X:\File1.xlsx")
wb2 = x1.workbooks.Open("X:\File2.xlsm")
x1.close("X:\File1.xlsx")
You can use DispatchEx to create a new instance of the application.
x1 = win32com.client.DispatchEx("Excel.Application")
x2 = win32com.client.DispatchEx("Excel.Application")
wb1 = x1.Workbooks.Open(.....
wb2 = x2.Workbooks.Open(.....
Roger
I tried to search many places but dit not see any example snippet of code about how to delete an existing worksheet in excel file by using xlutils or xlwt with python. Who can help me, please?
I just dealt with this and although this is not generally a good coding choice, you can use the internal Workbook_worksheets to access and set the worksheets for a workbook object.
write_book._Workbook__worksheets = [write_book._Workbook__worksheets[0]]
this would strip everything but the first worksheet associated with a Workbook
I just wanted to confirm that I got this to work using the answer David gave. Here is an example of where I had a spreadsheet (workbook) with 40+ sheets that needed to be split into their own workbooks. I copied the master workbook removed all but the one sheet and saved to a new spreadsheet:
from xlrd import open_workbook
from xlutils import copy
workbook = open_workbook(filepath)
# Process each sheet
for sheet in workbook.sheets():
# Make a copy of the master worksheet
new_workbook = copy.copy(workbook)
# for each time we copy the master workbook, remove all sheets except
# for the curren sheet (as defined by sheet.name)
new_workbook._Workbook__worksheets = [ worksheet for worksheet in new_workbook._Workbook__worksheets if worksheet.name == sheet.name ]
# Save the new_workbook based on sheet.name
new_workbook.save('{}_workbook.xls'.format(sheet.name))
The following method does what you need:
def deleteAllSheetBut(workingFolder, xlsxFILE, sheetNumberNotToDelete=1):
import win32com.client as win32
import os
excel = win32.gencache.EnsureDispatch('Excel.Application')
excel.Visible = False
excel.DisplayAlerts = False
wb = excel.Workbooks.Open( os.path.join( workingFolder, xlsxFILE ) )
for i in range(1, wb.Worksheets.Count):
if i != sheetNumberNotToDelete:
wb.Worksheets(i).Delete()
wb.Save()
excel.DisplayAlerts = True
excel.Application.Quit()
return
not sure about those modules but u can try win32
from win32com import client
def delete(self, number = 1):
"""
(if the sheet is the first use 1. -1 to use real number)
example: r.delete(1)
"""
sheetnumber = int(number) - 1