I am trying to open a Word document using the win32com.client, read in the headers from the document and then write them to an Excel file. I can successfully open the Word file, read in the headers and then print them to the screen.
Here is my code:
import win32com.client
import openpyxl
Excel_File = "header.xslx"
Create a new Excel workbook
workbook = openpyxl.Workbook()
Select the default sheet (usually named 'Sheet')
sheet = (workbook.active)
data = ['Req_Name']
# Create a Word application instance
word = win32com.client.Dispatch('Word.Application')
#Open the Word document
document = word.Documents.Open('header.docx')
#Access headers using the Document object
for headings in iter_headings(document.Paragraphs):
your text**print(headings.Range.Text)
Req_Name=(headings.Range.Text)
sheet.append(row)
workbook.save(Excel_File)
workbook.close()
Close the Word document (optional)
document.Close()
word.Quit()
Here is the output to the screen which is all of the headers in this test Word document
Test 1 Header
Test 2 Header
Test 3 Header
Test 4 Header
Test 5 Header
Test 6 Header
I think that I need to write the output data to a variable or list and then write that to Excel. But I am stumped on the mechanics.