Search code examples
python-3.xexport-to-excelpywin32

Creating a new Excel File in pywin32


I'm writing a program that, summarized, takes a notepad file and saves it as a excel file.

Right now my program opens up a blank excel file I have created, just "Book1.xls":

xlApp = Dispatch("Excel.Application")
xlApp.Visible=0
xlWb = xlApp.Workbooks.Open(file_path+"/Book1.xls")
workBook = xlApp.ActiveWorkbook
sheet = xlApp.ActiveSheet

and it uses Book1.xls to write into and format as is required, then saves it as another file name using

workBook.SaveAs(new_file_path+'/UpdatedSheet.xls')

I want to know how to simply create a new excel file to write to, then save as a file. Without the need of having Book1.xls already created in a specific directory.


Solution

  • You can create a new workbook using the Add method of the Workbooks object:

    >>> import win32com.client as win32
    >>> excel = win32.Dispatch("Excel.Application")
    >>> workbook = excel.Workbooks.Add()
    >>> workbook.SaveAs(new_file_path+'/UpdatedSheet.xls')