Share on Google+Share on Google+

JTextArea to Word Document

In this section, you will learn how to write the data into word document file through the textarea.

JTextArea to Word Document

Jakarta POI has provided several classes that enable us to perform read, write operations with ms word file. Here we are going to write the data into word document file through a swing component.

You can see in the given code, we have allowed the user to enter data in textarea. As the user clicked the 'Save' button after entering the data, the data will get saved in the word file using POI classes. And you can view your file by clicking the 'View' button. This is possible due to Runtime class.

Here is the code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class TextAreaInDocument extends JFrame {
	JTextArea area;
	JScrollPane pane;
	JButton b1, b2;
	File file = new File("C:/New.doc");

	private static void writeDoc(String FileName, String content) {
		try {
			POIFSFileSystem fs = new POIFSFileSystem();
			DirectoryEntry directory = fs.getRoot();
			directory.createDocument("WordDocument", new ByteArrayInputStream(
			FileOutputStream out = new FileOutputStream(FileName);
		} catch (Exception ex) {

	TextAreaInDocument() {
		area = new JTextArea(5, 30);
		area.setFont(new Font("courier New", Font.BOLD, 12));
		pane = new JScrollPane(area);
		b1 = new JButton("Save");
		b2 = new JButton("View");
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String text = area.getText();
				String f = file.getPath();
				writeDoc(f, text);
		b2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					Runtime rt = Runtime.getRuntime();
					rt.exec("cmd.exe /C start C:/New.doc");
				} catch (Exception ex) {
		JPanel p = new JPanel();

	public static void main(String[] args) {
		TextAreaInDocument doc = new TextAreaInDocument();


On clicking the button 'Save', the text will get saved in the word file. You can view your word file  by clicking the 'View' button.



Posted on: May 19, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.