Word Py
Word Py
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
try:
# Open template
doc = word.Documents.Open(str(self.template_path))
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.")
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()