Hi, is there any way for me to update the contents inside a word or text file using perspective or webdev.
For example, I have a large word document for books, and one field is called ISBN: FJ2JKLJ51KAIU11 , I want to be able to update that field without opening the word document.
I know I can do it with docx in python, but i am not able to install libraries in ignition, any help would be appreciated, thanks!
Ignition has system functions for reading and writing files, which will work well for plain text files:
You should be able to use the readFileAsString and writeFile functions.
Word documents require a bit more work. There is a good example here showing how to use Apache POI within Ignition (no external library required):
I've modified it slightly to read a file, modify the ISBN and save it again:
import re
from java.io import FileOutputStream, FileInputStream, IOException
from org.apache.poi.xwpf.usermodel import XWPFDocument
filePath = "someFile.docx" #Modify this with your Word document file path
# New ISBN number to replace with
newISBN = "AAAAAAA"
# Regular expression pattern to match the ISBN number
pattern = re.compile(r'ISBN:\s*([a-zA-Z0-9]+)')
# Initialize file input and output streams outside the try block
fis = None
fos = None
try:
# Load the Word document
fis = FileInputStream(filePath)
doc = XWPFDocument(fis)
# Iterate through paragraphs
for paragraph in doc.getParagraphs():
# Concatenate text from all runs within the paragraph. Sometimes the search string isn't always in a single run.
text = ""
for run in paragraph.getRuns():
text += run.getText(0)
if text:
# Use regex to find matches
matches = pattern.findall(text)
for match in matches:
# Replace only the ISBN number with the new ISBN
modified_text = text.replace(match, newISBN)
# Clear existing runs in the paragraph
for i in reversed(range(paragraph.getRuns().size())):
paragraph.removeRun(i)
# Insert the modified text into a new run in the paragraph
run = paragraph.createRun()
run.setText(modified_text)
# Save the modified document
fos = FileOutputStream(location)
doc.write(fos)
print("ISBN replacement completed successfully.")
except IOException as e:
e.printStackTrace()
finally:
# Close streams in finally block to ensure they are always closed, even if an exception is thrown somewhere
try:
if fos:
fos.close()
if fis:
fis.close()
except IOException as e:
e.printStackTrace()
Are you aware that using perspective or webdev, the docx file must be accessible and writable by the gateway service because the python scripts invoked by perspective or webdev are executed in the gateway or perspective scope?