Java uses POI to read and modify Word

Source: Internet
Author: User
Tags java web
 

Java programming to achieve the operation of Word without VB that programming language easy to come by some open source components, including Jacob, Poi and so on, and poi most widely used, word2003 and 2007 of the read and write word operations are very convenient. It's an Apache project that has already released its first version as early as 2001, an old Apache project that has now gone through 10 years, with the latest version being the 3.8 beta version. This is the version below that shows how to implement read and overwrite values for word.

All the source code in this article can be obtained by downloading POI to the word read-write operation instance Source (3).

1. Download

Download the 3.8BETA4 version, please remember to download the version, other versions read the Word template and overwrite content to generate a new file, when you open a new file prompts "Word cannot read the document, the document may be corrupted." ", see the figure below

Low version POI error generating Word document open

2. Integrated into the project

This step is very simple, as long as the download after the extracted Poi-3.8-beta4-20110826.jar and Poi-scratchpad-3.8-beta4-20110826.jar two files to the Java Web Project's lib directory on the line

3. Make Word template

Replace the values you need to change with code, such as if you need to change the value of the name, which can be represented in the template by name. See the Doc file in the Appendix for details.

4. Call interface method to implement read and write operations on word

The whole process is to read the template first, then modify the content, then regenerate the new document to save to the local or output file stream provides the download, the following is the generation of new documents and output file stream two ways of code snippets, detailed code see the following code Readwriteword () two overloaded methods.

==========================================================================

====================== How to generate new documents:: ==========================

Package work.tool;

Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.util.Iterator;
Import Java.util.Map;

Import Javax.servlet.http.HttpServletResponse;

Import org.apache.poi.hwpf.HWPFDocument;
Import Org.apache.poi.hwpf.model.FieldsDocumentPart;
Import Org.apache.poi.hwpf.usermodel.Field;
Import Org.apache.poi.hwpf.usermodel.Fields;
Import Org.apache.poi.hwpf.usermodel.Range;

/**
* Implementation of Java with POI implementation of Word read and modify operations
* @author FENGCL
*
*/
public class Readandwritedoc {

/**
* Implementation of Word read and modify operations
* @param filePath Word template path and name
* @param map to be populated with data, read from the database
*/
public static void Readwriteword (String filePath, map<string,string> Map) {
Reading Word templates
String Filedir = new File (Base.getfile (), http://www.cnblogs.com/http://www.cnblogs.com/... /doc/"). Getcanonicalpath ();
FileInputStream in = null;
try {
in = new FileInputStream (new File (FilePath));
catch (FileNotFoundException E1) {
E1.printstacktrace ();
}
Hwpfdocument HDT = null;
try {
HDT = new Hwpfdocument (in);
catch (IOException E1) {
E1.printstacktrace ();
}
Fields Fields = Hdt.getfields ();
Iterator<field> it = Fields.getfields (Fieldsdocumentpart.main). iterator ();
while (It.hasnext ()) {
System.out.println (It.next (). GetType ());
}

Reading Word text content
Range range = Hdt.getrange ();
System.out.println (Range.Text ());
Replace text content
For (map.entry<string,string> Entry:map.entrySet ()) {
Range.replacetext ("$" + entry.getkey () + "$", Entry.getvalue ());
}
Bytearrayoutputstream ostream = new Bytearrayoutputstream ();
String fileName = "" +system.currenttimemillis ();
FileName = = ". Doc";
FileOutputStream out = null;
try {
out = new FileOutputStream ("e:\\test\\" +filename,true);
catch (FileNotFoundException e) {
E.printstacktrace ();
}
try {
Hdt.write (ostream);
catch (IOException e) {
E.printstacktrace ();
}
Output byte stream
try {
Out.write (Ostream.tobytearray ());
catch (IOException e) {
E.printstacktrace ();
}
try {
Out.close ();
catch (IOException e) {
E.printstacktrace ();
}
try {
Ostream.close ();
catch (IOException e) {
E.printstacktrace ();
}
}

====================== output file streaming mode: ==========================


/**
* Implementation of Word read and modify operations
* @param response response, set the generated file type, file header encoding and file name, and output
* @param filePath Word template path and name
* @param map to be populated with data, read from the database
*/
public static void Readwriteword (HttpServletResponse response, String FilePath, map<string, string> Map) {
Reading Word template files
String Filedir = new File (Base.getfile (), http://www.cnblogs.com/http://www.cnblogs.com/... /doc/"). Getcanonicalpath ();
FileInputStream in = new FileInputStream (New File (filedir+ "/laokboke.doc"));
FileInputStream in;
Hwpfdocument HDT = null;
try {
in = new FileInputStream (new File (FilePath));
HDT = new Hwpfdocument (in);
catch (Exception E1) {
E1.printstacktrace ();
}

Fields Fields = Hdt.getfields ();
Iterator<field> it = Fields.getfields (Fieldsdocumentpart.main). iterator ();
while (It.hasnext ()) {
System.out.println (It.next (). GetType ());
}

Replace the specified field for the content of the read Word template
Range range = Hdt.getrange ();

For (map.entry<string,string> Entry:map.entrySet ()) {
Range.replacetext ("$" + entry.getkey () + "$", Entry.getvalue ());
}

Output Word content file streams, providing downloads
Response.reset ();
Response.setcontenttype ("Application/x-msdownload");
String fileName = "" +system.currenttimemillis () + ". Doc";
Response.AddHeader ("Content-disposition", "attachment; Filename= "+filename);
Bytearrayoutputstream ostream = new Bytearrayoutputstream ();
OutputStream servletos = null;
try {
Servletos = Response.getoutputstream ();
Hdt.write (ostream);
Servletos.write (Ostream.tobytearray ());
Servletos.flush ();
Servletos.close ();
catch (Exception e) {
E.printstacktrace ();
}

}
}
==========================================================================

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.