http://www.technicalpage.net/search/label/SQL

Create MS Word document using Apache POI

Create a new word document(docx) and write(Text) in it .

You can create Microsoft documents (Word, Excel, PowerPoint) using Apache POI. In below code, I have used the poi-bin-4.1.1 from “poi.apache.org/download”.
 

package msWord;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class CreateMSWordDocument {

      public static void main(String[] args) throws Exception {
           
            File file = new File("D:\\NewFolder\\Practice.docx");//Practice.docx file will be created , if already exists, then replaces the previous one.
            FileOutputStream outputFile = new FileOutputStream(file);
           
            //Create document
            XWPFDocument docx = new XWPFDocument();
           
            //Add Paragraph
            XWPFParagraph pgraph = docx.createParagraph();
           
            XWPFRun run = pgraph.createRun();
           
            //Write text in the document
            run.setText("This text will be in the word document.");
            //run.setColor(Color.RED);//will be discussed in separate lesson.
            run.setBold(true);
            run.setFontSize(30);
            docx.write(outputFile);
            outputFile.close();
           

            System.out.println(" MS Word Document Created.");
      }

}

Output:
 MS Word Document Created.

No comments:

Post a Comment