簡體   English   中英

使用 Apache POI 的 xwpfd 在表格的單元格中插入圖像

[英]Insert image in a table's cell using Apache POI's xwpfd

我正在開發一個需要將結果以表格格式寫入.docx的程序。 我需要從某些表格單元格中的文件夾中寫入圖像,但我一直無法弄清楚該怎么做。 我看到的解決方案是在文檔中插入圖像。

Student student = new Student ();
XWPFDocument Document = new XWPFDocument ();
XWPFTable table = document.createTable(20,2);
XWPFTableRow rows =null;
XWPFTableCell cell = null;

for (int i=0; i<20; i++) {
   rows = table.getRow(i)
   student = studentList.get(i);

   //first column
   cell = rows.getCell(0);
   //add image to this cell. The path to the image can be gotten from student.getImagePath and the image itself in BufferedImage can be gotten from student.getImage

   //second column
   cell = rows.getCell(1);
   cell.setText(student.getDetails);
}

我能夠解決它。 下面是工作代碼:

Student student = new Student ();
String [] details = {"Detail1: ", "Detail2: ", "Detail3: ", "Detail4: ", "Detail5: "};
FileInputStream fis;
String imageName;
int index;
File file;

XWPFDocument document = new XWPFDocument(); //create table
XWPFTable table;
XWPFParagraph paragraph;
XWPFRun run;
XWPFTableRow rows = null;
XWPFTableCell cell = null;

//Write Hall Name at the top of the word document
paragraph = document.createParagraph();
run = paragraph.createRun();
run.setUnderline(UnderlinePatterns.WORDS);
run.setText("Hall Name: " + hallName);
run.addBreak();

table = document.createTable(rw, cl);
table.getCTTbl().getTblPr().unsetTblBorders();

for (int i=0; i<rw; i++) {
    rows = table.getRow(i);
    student = studentList.get(i);

    //First column
    cell = rows.getCell(0);
    paragraph = cell.addParagraph();
    run = paragraph.createRun();
    if (student.getImagePath() == null) {
        run.setText("Image Unavailable");
    } 
    else {
        fis = new FileInputStream(student.getImagePath());
        index = student.getImagePath().lastIndexOf('\\') + 1;
        imageName = student.getImagePath().substring(index);
        run.addPicture(fis, XWPFDocument.PICTURE_TYPE_JPEG, imageName, Units.toEMU(100), Units.toEMU(100));
    }

    //Second column
    cell = rows.getCell(1);
    paragraph = cell.addParagraph();
    run = paragraph.createRun();
    run.setText(details[0] + student.getRegNumber());
    run.addBreak();
    run.setText(details[1] + student.getName());
    run.addBreak();
    run.setText(details[2] + student.getExamNumber());
    run.addBreak();
    run.setText(details[3] + student.getTableNumber());
    run.addBreak();
    run.setText(details[4] + student.getLevel());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM