问题描述:

I will try to explain what I need.

I have a text that contains both normal-sized and subscript text (e.g. oxygene O2) which I would like to write to docx file using apache poi 3.9 library. I get either all text normal sized or subscript. Is there a way to do that?

Here is my code:

import org.apache.poi.xwpf.usermodel.XWPFDocument;

import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import org.apache.poi.xwpf.usermodel.XWPFRun;

import org.apache.poi.xwpf.usermodel.VerticalAlign;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class ApachePOI {

public static void main(String[] args) {

XWPFDocument document = new XWPFDocument();

XWPFParagraph paragraph = document.createParagraph();

XWPFRun run = paragraph.createRun();

run.setText("Oxygene - O");

run.setSubscript(VerticalAlign.SUBSCRIPT);

run.setText("2");

try {

FileOutputStream fos = new FileOutputStream("test.docx");

document.write(fos);

fos.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

网友答案:

Yes, try this code -

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.VerticalAlign;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ApachePOI {    
    public static void main(String[] args) {

    XWPFDocument document = new XWPFDocument(); 
    XWPFParagraph paragraphOne = document.createParagraph();

    paragraphOne.setAlignment(ParagraphAlignment.CENTER);

    XWPFRun paragraphOneRunOne = paragraphOne.createRun();
    paragraphOneRunOne.setFontSize(25);
    paragraphOneRunOne.setBold(true);
    paragraphOneRunOne.setText("Oxygene - O");

    XWPFRun paragraphOneRunTwo = paragraphOne.createRun();
    paragraphOneRunTwo.setFontSize(17);
    paragraphOneRunTwo.setBold(true);
    paragraphOneRunTwo.setSubscript(VerticalAlign.SUBSCRIPT);
    paragraphOneRunTwo.setText("2");

    try {
        FileOutputStream fos = new FileOutputStream("C://test.docx");
        document.write(fos);
        fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

相关阅读:
Top