Cristian
Cristian

Reputation: 93

Is it possible to use only the name of the files instead of writing out the entire path?

Is it possible to use only the name of the files instead of writing out the entire path in line 4 and 5?

 [1] from win32com import client
 [2] excel = client.Dispatch("Excel.Application")
 [3] word = client.Dispatch("Word.Application")
 [4] doc = word.Documents.Open(r"C:\Users\crist\word_automation\Summary_template\Table1.docx")
 [5] book=excel.Workbooks.Open(r"C:\Users\crist\word_automation\Summary_template\Table1.xlsx")
    sheet = book.Worksheets(1)
    sheet.Range("A1:D5").Copy()    
    wdRange = doc.Content
    wdRange.Collapse(0)
    wdRange.PasteExcelTable(False, True, False) 
    
    import os
    os.remove('Table2.xlsx')
    
    book.SaveAs('Table2.xlsx')
    book.Close()
    excel.Quit()
    doc.SaveAs('TableOne.docx')
    doc.Close()
    word.Quit()

I've tried doing this, but it gives me an error:

doc = word.Documents.Open('Table1.docx')
book = excel.Workbooks.Open('Table1.xlsx')

com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Excel', "Sorry, we couldn't find Table1.xlsx. Is it possible it was moved, renamed or deleted?", 'xlmain11.chm', 0, -2146827284), None)

Updated Code:

from win32com import client
import os
os.chdir(r"C:\Users\crist\word_automation\Summary_template")

excel = client.Dispatch("Excel.Application")
word = client.Dispatch("Word.Application")
doc = word.Documents.Open('Table1.docx')
book = excel.Workbooks.Open('Table1.xlsx')
sheet = book.Worksheets(1)
sheet.Range("A1:D5").Copy()    
wdRange = doc.Content
wdRange.Collapse(0)
wdRange.PasteExcelTable(False, True, False) 

os.remove('Table2.xlsx')

book.SaveAs('Table2.xlsx')
book.Close()
excel.Quit()
doc.SaveAs('TableOne.docx')
doc.Close()
word.Quit()

Upvotes: 0

Views: 72

Answers (1)

MattDMo
MattDMo

Reputation: 102902

Yes, it is possible. Simply move your import os line to the top of the file (before or after the win32com import, it doesn't matter), then on the next line put

os.chdir(r"C:\Users\crist\word_automation\Summary_template")

You can now omit the full paths you send to word.Documents.open() and excel.Workbooks.open(), like you show in the lower part of your question.

Upvotes: 0

Related Questions