Search code examples
apache-poiapache-poi-4

Need to create exponential data(number) in single cell in apache poi without using paragraph.break


I am constructing a row with 8 columns and Need to create exponential data(number) in single cell in apache poi WORD without using paragraph.break .

second column exponential data without pagebreak


Solution

  • If the content (2) shall be superscript, then there are two possibilities using Microsoft Word. Either really superscript align or set the text position away from the text base line. For both the (2) must be in it's own text run.

    Superscript alignment can be achieved using XWPFRun.setSubscript having VerticalAlign.SUPERSCRIPT.

    Text position can be set using XWPFRun.setTextPosition where int val is of measurement unit half pt.

    Example:

    import java.io.FileOutputStream;
    
    import org.apache.poi.xwpf.usermodel.*;
    
    public class CreateWordSuperScript {
    
     public static void main(String[] args) throws Exception {
    
      XWPFDocument document= new XWPFDocument();
      XWPFParagraph paragraph;
      XWPFRun run;
    
      paragraph = document.createParagraph();
      run = paragraph.createRun();  
      run.setText("6  ");
      run=paragraph.createRun();  
      run.setText("(2)");
      run.setSubscript(VerticalAlign.SUPERSCRIPT); // superscript (2)
    
      paragraph = document.createParagraph();
      run=paragraph.createRun();  
      run.setText("6  ");
      run=paragraph.createRun();  
      run.setText("(2)");
      run.setTextPosition(11); // (2) position = baseline + 11 half pt ~ 5.5 pt
    
      FileOutputStream out = new FileOutputStream("word.docx"); 
      document.write(out);
      out.close();
      document.close();
     }
    }