0% found this document useful (0 votes)
8 views2 pages

Word Py

The document outlines a Python class, WordHandler, designed to automate the updating of bookmarks in a Word document template using the win32com.client library. It logs actions and errors while ensuring the output file is saved in a specified directory with a formatted name. The class takes parameters for a WIR number and revision, and updates various bookmarks with provided data, handling exceptions appropriately.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Word Py

The document outlines a Python class, WordHandler, designed to automate the updating of bookmarks in a Word document template using the win32com.client library. It logs actions and errors while ensuring the output file is saved in a specified directory with a formatted name. The class takes parameters for a WIR number and revision, and updates various bookmarks with provided data, handling exceptions appropriately.

Uploaded by

HQHome
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import datetime

import logging
import win32com.client
from pathlib import Path
from constants import WordFilePath, Word_folder

# Configure logging
logging.basicConfig(
filename="word_handler.log", # Log file
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
)

class WordHandler:
def __init__(self, next_wir_number, rev):
self.next_wir_number = str(next_wir_number).zfill(5) # Format WIR No to 5
digits
self.rev = rev # Fixed capitalization for consistency
self.template_path = Path(WordFilePath)
self.save_folder = Path(Word_folder)
self.word_path = Path(WordFilePath)
self.save_folder.mkdir(parents=True, exist_ok=True) # Ensure directory
exists

def update_bookmarks(self, data):


word = win32com.client.Dispatch("Word.Application")
word.Visible = False # Run in the background

try:
# Open template
doc = word.Documents.Open(str(self.template_path))

# Define the bookmark values


bookmark_values = {
'WIRNo': f"{self.next_wir_number} - R {self.rev}", # Fixed en-dash
issue
'CreatedDate1': datetime.date.today().strftime('%d %b %Y'),
'CreatedDate2': datetime.date.today().strftime('%d %b %Y'),
'CreatedDate3': datetime.date.today().strftime('%d %b %Y'),
'InspectionDate': data['Inspection_Date'].strftime('%d %b %Y'),
'PlotNo': data['villa'],
'Part': data['part'],
'Level': data['level'],
'Description': data['description'],
}

print(bookmark_values)
logging.info(f"Updating bookmarks with data: {bookmark_values}")

# Update bookmarks
for bookmark, value in bookmark_values.items():
if doc.Bookmarks.Exists(bookmark): # More efficient check
doc.Bookmarks(bookmark).Range.Text = str(value)
else:
logging.warning(f"Bookmark '{bookmark}' not found in the
template.")

# Define save path


save_path = self.save_folder / f"WIR-{self.next_wir_number}-
R{self.rev}.docx"

# Save as new Word file


doc.SaveAs2(str(save_path), FileFormat=16) # FileFormat=16 for DOCX
logging.info(f"Word file saved successfully: {save_path}")

except Exception as e:
logging.error(f"Error updating Word file: {e}")
print(f"Error updating Word file: {e}")

finally:
if 'doc' in locals(): # Ensure document is closed if opened
doc.Close()
word.Quit()

You might also like