Search code examples
androiddocx

I want to convert text of Edit Text to Docx in Android


I want to convert text in edit text to docx format directly and store in Internal Storage .

I tried searching on google but hardly I didn't find anything.

   String text = editText.getText().toString();
   String FILE_NAME1 = sample.docx // not working

    //  File file = new File("/storage/emulated/0");
    String pathTXT = Environment.getExternalStorageDirectory() + "/Kibo Directory" + "/" + FILE_NAME1 ;

    FileOutputStream fos = null;
    try {

        fos = new FileOutputStream(pathTXT); // This is creating file in internal (outside)

        //   fos = new FileOutputStream(file);

       // fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
        fos.write(text.getBytes());

        Toast.makeText(this, "Saved to" + pathTXT + "/" + FILE_NAME1, Toast.LENGTH_LONG).show();

    } catch (Exception e)
    {
        e.printStackTrace();
    }

I am giving name as sample.docx which is saving in docx format but it is not valid one.


Solution

  • You can use apache POI :

    Create a function like this :

        private static void createDocx(String[] lines) throws IOException {
    
    
        XWPFDocument xwpfDocument = new XWPFDocument();
    
        FileOutputStream fileOutputStream = new FileOutputStream(new File("yourfilepath/filename.docx"));
    
    
    
        for(String s:lines) {
    
    
            XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph();
    
    
            XWPFRun xwpfRun = xwpfParagraph.createRun();
    
            xwpfRun.setText(s);
    
        }
        xwpfDocument.write(fileOutputStream);
        fileOutputStream.close();
    }
    

    and pass your Text as String array (each line of your text will be a member of the array) to it.

    Don't forget to add Apache POI jars libraries to your project.