2015-10-07 122 views
2

将图像插入表格单元格我正在研究一个程序,该程序需要以表格格式将结果写入.docx。我需要在某些表格单元格中的文件夹中写入图像,但我一直无法弄清楚该如何操作。我看到的解决方案是将图像插入文档中。使用Apache POI的xwpfd

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); 
} 
+0

你问题很模糊。你说“我正在制定一个计划......”;提供该程序的详细信息可能有助于回答你的问题。 – gobrewers14

+0

发布你迄今为止所做的一些代码,你更有可能吸引好的答案。另外,请在添加标签之前阅读标签说明。可能有关于如何使用(或不使用)的重要信息。 – Anders

+0

创建表格单元格,在那里创建一个段落,在那里创建一个运行,然后将图片添加到该运行,就像其他任何方式一样?这是一个造成问题的表格有什么特别之处? – Gagravarr

回答

2

我能够整理出来。以下是工作代码:

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()); 
}