Solved

replace text in word file

Posted on 2006-11-03
34
694 Views
Last Modified: 2009-12-16
Hi,

Using ASP, is it possible to open a .doc, and replace a word in it?

The web server does not have MS Word installed on there.

The idea:
1. Use a word doc as a template.
2. tag doc template areas with "dear <FIRSTNAME>"
3. Read/open the file and replace with yoru variable over <FIRSTNAME>

I've seen some other solution by willi70
 but I get permission errors and I think this is dependant on the server havign Word. I can purchase Word on the server if needed)
http://www.experts-exchange.com/Web/Web_Languages/ASP/Q_20736795.html?query=edit+word+doc&topics=97


Thanks,

0
Comment
Question by:mrduckers
  • 12
  • 12
  • 5
  • +2
34 Comments
 
LVL 10

Expert Comment

by:thefritterfatboy
ID: 17866534
Would it be possible for your document to be Word 2003+ format? (I think it would open in 2000 but definately not in the '97 version)

If so, you could look at using XML to generate a document. If you open your document in Word 2003 and select "Save As.." you can select the XML format. Renaming this document to have a .doc extension is advisable - Windows likes to handle XML document to check their type before opening but it's not foolproof - having a .doc extension ensures Office opens the document.

Once in XML format, you can easily open the file as a text file on the server and replace what you need to replace.

If not, you'll need to install word on the server.
0
 

Author Comment

by:mrduckers
ID: 17866572
Lets say I install word on the server -how would I approach this.

NOTE: the end user is dumb.

I will be creating a form for them to enter n the name, address and other fields which will populate the word template. this should then prompt them to download after they click submit.

The file can be saved and processed on the server but the end user should just have to fillin the fields and click submit and save.

0
 
LVL 10

Assisted Solution

by:thefritterfatboy
thefritterfatboy earned 50 total points
ID: 17866832
When Word is installed, it offers some pretty advanced stuff via the COM components. (It's also VERY resource-intense, so if avoidable, try to avoid using it. It's also prone to random crashes / staying in memory.)

The document object allows object-oriented access to the document and allows you to change values and aspects of the document programatically.

Set WordApp = CreateObject("word.application")
          Set WordDoc = WordApp.Documents.open("c:\file.doc")

'you can go to selections in the document using the document object

WordDoc.Selection.GoTo what:=wdLine, which:=wdGoToAbsolute, Count:=1 'goto line 1
WordDoc.Selection.GoTo what:=wdGoToTable, which:=wdGoToAbsolute, Count:=1 'goto table 1

I'd strongly advise against installing word on the web server, though. A few requests at the same time and your server pretty much just hangs. Seriously consider a third-party tool for editing/creating word documents. They are designed for server use - Office is not.
0
 

Author Comment

by:mrduckers
ID: 17870982
Thanks for your insightful information

Do you have example of 3rd party products?

0
 
LVL 25

Expert Comment

by:kevp75
ID: 17871453
i'm curios as to why go this route?

Why not:
1) Have your form
2) Save the data to a db of some kind
3) Export the results of the recordset to a word document?
0
 

Author Comment

by:mrduckers
ID: 17871498
The word document is a letter template.

The letter template would be used on a site where people could use the the form will to fill out their personal details and address on the word document.

What you said is ok but how would i export the results of the recordset to the word document.?
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17871513
have a link that says 'Export To Word'

something like:
<a href="/page.asp?export=word">Export To Word</a>

on the same page (page.asp)
at the top of the page:

expWord = request.querystring("export")
if expWord = "word" then
  Response.ContentType = "application/vnd.ms-word"
end if
0
 

Author Comment

by:mrduckers
ID: 17871599
I think I tired this and it ask me to install import features.

In addition, I think it give me an unformatted couriour font document.

Am I correct or is there another method?
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17871761
you think?

have you tried like I showed?  (I've never had a problem with this method)

try what I said.  Put in the link on your page to link to iteslf with the querystring I posted...

if what I initially posted doesn't work try:

expWord = request.querystring("export")
if expWord = "word" then
   Response.Buffer = True
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "inline; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like
end if
'just make sure this is at the top of your page
0
 

Author Comment

by:mrduckers
ID: 17871929
on the code above, is the content stored as a varible?

strContent = "xxx" ?
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17871963
i don't see strContent anywhere in this entire thread

have you tried what I have suggested yet?  (or are we just wasting time here?)
0
 

Author Comment

by:mrduckers
ID: 17872741
I've tried somethign like this.

It prompts you to save the page and you select "All files" and change the extension.

After that you go and open the file and the content from that page is in the doc and unformatted.

I need to use the original Word template as it contains formatting.


Regards,
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17873520
ok, since you aren't going to try the solutions (which do work...especially the second one), I do feel you are wasting our time now.

Good Luck to you...I'm done
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17873687
i see what goes on now.

I'm adding in an export to word/excel/pdf to a time card application I'm building.

I notice that if I have this:
 Response.AddHeader "content-disposition", "inline; filename = ASP_Word_Doc.doc"

the formatting stays, however once I make it an attachment ( Response.AddHeader "content-disposition", "attachment; filename = ASP_Word_Doc.doc" )

I lose the formatting.  What I ended up doing was moving the needed styles to the page directly (CSS), rather than linking the CSS file, and whammo.  it worked
0
 

Author Comment

by:mrduckers
ID: 17877694
Your above code works, but how do I replace a field in there?

Lets says <FIRSTNAME> in doc with request.form("firstname") from a form?
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17877763
ok, what you should be doing is adding this code to the page that processes the form, not on the form page itself.

so if you have page1.asp which contains the form.  You then click submit, and it goes to another page(page2.asp) which does the processing.  Process your form results as you wish, display the results, then Have the code on that page to export the results to word

(this is what I said originally in my first post)
0
 

Author Comment

by:mrduckers
ID: 17877804
I can increase the points to 500 if you can supply/alter the code below.

Lets say in my word document has soem text in it <NAME> - I want to replace it with my form field "name" as below.

If I use:

form.asp
<form action="process.asp?export=word" method="post">
<input type="name">
<input type="submit">
</form>

process.asp
<%
expWord = request.querystring("export")
if expWord = "word" then
   Response.Buffer = True
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "inline; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like
end if
%>

Thanks.
0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 25

Expert Comment

by:kevp75
ID: 17878363
form.asp
<form action="process.asp" method="post">
<input type="text" name="FieldName">
<input type="submit">
</form>

process.asp
<%
expWord = request.querystring("export")
if expWord = "word" then
   Response.Buffer = True
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "attachment; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like, also change this to inline if you want to make the browser attempt to open it first
end if
strFieldName = replace(request.form("FieldName"),"'","''")
response.write("<a href='/process.asp?expWord=word'>" & strFieldName & "</a>")
%>

0
 

Author Comment

by:mrduckers
ID: 17878559
Hi Kev,

I don't see how the above code will swap the form field "Name" with the text "<NAME>" in the word document but i'll give it a try.

All I see ti doing is putting the name in the link.

Regards,
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17878587
sorry.

do this instead.  Keep form.asp the way I posted.

make process.asp

<%
   Response.Buffer = True
   response.write(replace(request.form("FieldName"),"'","''"))
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "attachment; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like, also change this to inline if you want to make the browser attempt to open it first
%>

instead
0
 
LVL 6

Expert Comment

by:gete
ID: 17879904
@kevp75, I think what happened is:
1) There is an _existing_ Word document written by user and then saved at web server machine, e.g as C:\template.doc
2) Inside template.doc, there is a word "<NAME>" serving as a place holder, i.e. similar to mail-merge operation
3) mrduckers want to generate a _new_ Word document which is basically a copy of template.doc, but with modified content, i.e. replacing "<NAME>" with "John Doe".

As it has been pointed in several occassions, the code you've given doesn't deal with any existing Word document serving as a template. If I may guess, your idea is to keep/have the template not in an existing Word document but rather in HTML/ASP code.

If the existing Word document is a must, as thefritterfatboy mentioned, it can be done by automating Word application via COM.
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17880815
very true gete, and it is a good possibility.

though my whole point with it,was to prevent him/her from having to go out and buy word so he/she cn install it on the server

if what gete states is true mrduckers, than you would have to go and make sure word is installed on the server, then give IUSR_machinename read write access to the folder that contains the word document, and follow the fritterfatboy's suggestions
0
 
LVL 10

Expert Comment

by:thefritterfatboy
ID: 17881119
If you need the documents to be Office 2000 friendly, then you will need to install Word on the server. (If this is the case - install Word 2000 - it is much less resource-intesive than Word 2003.)

If you are pretty sure your users will be using Word 2003 (as i suspect most users are), then you can create word documents in XML, as suggested earlier. Microsoft are very keen on developers using XML to create / edit documents on the fly as it is future proof. (We all remember the 1997 - 2000 file format change which caused a lot of problems!) This decision, on paper, is the better option. But obviously you need to consider the real world aspects of your system and whether you need Office 2000 compatability.

Post back once you have made a decision and we can help you through your code to get it working.
0
 

Author Comment

by:mrduckers
ID: 17885148
I'm not too keen on installing Word on the server as it might effect our other sites/clients.

This doesn't leave too many options right?

Does this mean I need to find a 3rd party component?
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17885224
no.  It means you need to try what I've been posting this entire thread.

I've given you the answer, now you need to try it out and tell us the results:

form.asp
<form action="process.asp" method="post">
<input type="text" name="FieldName">
<input type="submit">
</form>



process.asp
<%
   Response.Buffer = True
   response.write(replace(request.form("FieldName"),"'","''"))
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "attachment; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like, also change this to inline if you want to make the browser attempt to open it first
%>
0
 

Author Comment

by:mrduckers
ID: 17887046
Hi Kev,

I already tried this yesterday. The above code doesn't do anything apart from ask me to save the file.

I needed to replace some copy in the word document.

Regards,
0
 
LVL 1

Expert Comment

by:NTJOCK
ID: 17887308
I don't mean to be rude.... but why are you trying to do this with ASP?  Why not just open a copy of the document and do a find/replace?  That's what we always used to do with placeholders.  

This is a bit like trying to design a robot to crush the bug in front of you.  It will cost you a substantial amount of time and energy when you could just step on it and be done.

The macro capability in word is pretty incredible.  

That said, Word is pretty much a proprietary file format and unless you rever to saving things as text you are going to eventually find unexpected events (surprises).

If you do store things in text files, then use the file i/o stuff to read a line and write a line.  Read from your template and write to the new file.  Just do a replace command on each line as you read and write it.  This is fast and efficient.  You are still stretching what ASP is for and it will punish you dearly for it with server performance and timeouts.

I'd actually also suggest looking at writing a VB app for this.  This is a classic OLE/OLAP application and auto-generating documents would be quicker in a VB app that was standalone.  Although, frankly the 20 cent solution here is a macro of a find/replace.

If you have *alot* of these you could switch it to a mail merge and specify the output as a new document.
0
 

Author Comment

by:mrduckers
ID: 17887315
The tool is a only respoitory of documents, manuals and some word document email templates.

From the tool the "client" wants to make things as easy as possible. Eg. populating the word document with the persons details.

I have suggested doign this through macros, but a person word security settings may be too high, and the client thinks the end user it too dumb to turn off.

Nevertheless, I don't think this is acheivable through ASP.


Regards,
0
 
LVL 1

Expert Comment

by:NTJOCK
ID: 17887391
UGH.... it may be achievable but a huge PIA (pain in the a)))

Why not store the links to the documents in a DB and just make it easy to find stuff that is a template.

I think Macros are the 30 minute solution.


I did find this when I googled...
http://www.powergrep.com/msword.html

Grep for MS-Word.  You might be able to run it under the covers either on the client side or the server side.

In either case, ASPupload will take some headache out of the file side.  I use it to "replicate" master documents (PDFs) to client specific folders as part of a ASP based process.

so what I would do is have the templates in a safe place.

Have the user "kick-off" the process.
Display some pretty graphics for them.
use Asp Upload to make a copy of the file.
store the filename in SQL.
Call a stored procedure in sql to do your command line dirty work.
Display the results of your "web process" to the user.

Get a coke and enjoy a laugh.... :)

I think security limitations will choke you trying to run command line processes from ASP.  So I'm suggesting circumventing that with SQL Server.  I know you can call all sorts of stuff through stored procedures.

You could also write the stuff to a file and then have a 5 minute job that runs whatever is in the queue (or a 2 minute timer)
and just have the pretty graphics animate for a few minutes and then go look for the result file.  

lol, kick it out to batch, display graphics for 30 seconds, check for file, if done display, else display graphics for 30 more seconds.

Let me know if that helps.
0
 
LVL 10

Expert Comment

by:thefritterfatboy
ID: 17887690
Kev,

Surely the correct order sould be;

process.asp
<%
   szHTML = "<html>My name is <NAME><!-- you can create / save a Word document in HTML. Either put the string here, or load the string from a file --></html>"
   Response.Buffer = True
   Response.ContentType = "application/vnd.ms-word"
   Response.AddHeader "content-disposition", "attachment; filename = ASP_Word_Doc.doc"  'you can change this filename to whatever you like, also change this to inline if you want to make the browser attempt to open it first
   response.write(replace(szHTML,"<NAME>", request.form("name")))

%>
0
 
LVL 25

Expert Comment

by:kevp75
ID: 17889144
@thefritterfatboy

it may be, but being frustrated as I was  (with all the "I think that won't wotk's") from the questioner, I tried it out exactly how I posted it, and it worked for me...

@the questioner
it's not a good idea to force the document to open in any circumstance, however if you read the comment I put in after the Response.AddHeader line you will see that I mentioned to change the attachment portion of that to inline....

since the answer is in front of your face, and since you are un-willing to do anything other than say "I think that won't work", it is obvious you are one of those people who won't take a suggestion because you are always right and everyone else on the planet is wrong.....good luck to you, hope you can figure it out on your own
0
 
LVL 1

Assisted Solution

by:NTJOCK
NTJOCK earned 50 total points
ID: 17889300
@kevp Your solution doesn't seem to do what he wants.  You're also being pushy/rude about his lack of interest in your solution.  Be professional.  Your solution does seem to open the document, but it doesn't meet the find/replace criteria.

I suspect that this is a legal/medical/government application where they have low-skill employees accessing pre-done documents.  Each employee then replaces <name> <problem> <address> with the right info and saves a new copy, prints, and disseminates "official" correspondence.  While it's a bit arcane it's a great way to save time when churning out alot of documents that have to be in one form or another.  Think state form letters about some state program where the language has to be "just so".

I think they were just exploring ASP as a way to do dirty work, not as a replacement for Word.  If anything my read on this is that they are trying to take as much "thinking" out of the user activity stream as possible.  This would be a good use of ASP.

1) Select issue
2) Enter personalization
3) Retrieve "base" document that can be processed.  (base document = personalization+template)

I could be very wrong here on what they are doing, but that is what I read.  Your code
0
 
LVL 10

Expert Comment

by:thefritterfatboy
ID: 17889386
Kev, I'm gonna have to agree with ntjock on this one. I think a sense of professionalism needs to be re-introduced into this thread.
0
 
LVL 6

Accepted Solution

by:
gete earned 150 total points
ID: 17890522
Now that we're clear that it's *required* to edit existing/precreated Word files and not generating a new one from scratch (HTML/ASP), continuing the discussion:

I'm thinking along what ntjock suggested. If the end users are not savvy enough and will be alarmed by macro security warnings, another idea is as follow:
1) User enters the info via a web form and click submit/download
2) Server make a copy of the Word document, e.g. template.doc
3) Server generate a VBScript (.vbs) file containing submitted info from web form and code to automate Word to modify template.doc in user's own PC
4) Server compress/zip both files and create a self-extracting executable with default action is to run the script.
This way template.doc needs no macro. I know it's complicated and step 4 requires yet another server side component to create zip/exe file. But that's an idea.

Regarding 3rd party component that's suggested earlier by thefritterfatboy, you may want to read this:
Considerations for server-side Automation of Office
http://support.microsoft.com/kb/257757

It lists several 3rd party vendors:

Aia Software B.V.
http://www.aia-itp.com (http://www.aia-itp.com)

Polar
http://www.polarsoftware.com (http://www.polarsoftware.com)

SoftArtisans
http://www.softartisans.com (http://www.softartisans.com)

SyncFusion
http://www.syncfusion.com (http://www.syncfusion.com)

Keylogix
http://www.activedocs.com
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

I have helped a lot of people on EE with their coding sources and have enjoyed near about every minute of it. Sometimes it can get a little tedious but it is always a challenge and the one thing that I always say is:  The Exchange of information …
Have you ever needed to get an ASP script to wait for a while? I have, just to let something else happen. Or in my case, to allow other stuff to happen while I was murdering my MySQL database with an update. The Original Issue This was written…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now