For android, replace the content in word documents with word.
Code structure:
The ljp.doc IN res/raw/is a word template with the following content:
The Code is as follows:
Package com. example. readandwritedoc; import java. io. byteArrayOutputStream; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java.net. URL; import java. util. hashMap; import java. util. iterator; import java. util. map; 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; import android. OS. bundle; import android. app. activity; import android. content. res. resources; import android. view. menu; import android. widget. toast; public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); Map
Map = new HashMap
(); Map. put (title, do you want to change the name of a blog); map. put (blog_name, l1976135784); map. put (domain_name, http://blog.csdn.net/laijunpeng); map. put (description, one-day program hit one day, normal study notes, IT blog .); This. writeDoc (map);} public void writeDoc (Map
Map) {try {// read the word template Resources res = super. getResources (); InputStream in = res. openRawResource (R. raw. ljp); HWPFDocument hdt = new HWPFDocument (in); Fields fields = hdt. getFields (); Iterator
It = fields. getFields (FieldsDocumentPart. MAIN ). iterator (); while (it. hasNext () {System. out. println (it. next (). getType ();} // read the content of the word text Range = hdt. getRange (); System. out. println (range. text (); // Replace the text content for (Map. entry
Entry: map. entrySet () {range. replaceText (entry. getKey (), entry. getValue ();} ByteArrayOutputStream ostream = new ByteArrayOutputStream (); String fileName = + System. currentTimeMillis (); fileName + =. doc; FileOutputStream out = new FileOutputStream (/sdcard/+ fileName, true); Toast. makeText (this, successfully saved to the sdcard directory, Toast. LENGTH_LONG ). show (); hdt. write (ostream); // output byte stream out. write (ostream. toByteArray (); out. close (); ostream. close ();} catch (IOException e) {e. printStackTrace ();} catch (Exception e) {e. printStackTrace () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}