POI操作word表格,添加单元格,单元格对齐方法(不必合并单元格)

添加单元格,直接对row进行create新的cell,则会导致新创建的单元格与前面的单元格不对齐的现象。

        //表格信息
        XWPFTable table = doc.createTable();
        table.setWidth("100%");
        //第一行
        XWPFTableRow row0=table.getRow(0);
        XWPFTableCell cell00=row0.getCell(0);
        XWPFRun run00=cell00.getParagraphs().get(0).createRun();
        run00.setFontSize(14);
        run00.setFontFamily("仿宋");
        run00.setText("一、课程基本信息");
        run00.setBold(true);

        //第二行
        XWPFTableRow row1=table.createRow();
            //第一列
        XWPFTableCell cell10=row1.getCell(0);
        XWPFRun run10=cell10.getParagraphs().get(0).createRun();
        run10.setText("课程名称");
            //第二列
        XWPFTableCell cell11=row1.createCell();
        XWPFRun run11=cell11.getParagraphs().get(0).createRun();
        run11.setText(courseInfo.getCourse_name());
            //第三列
        XWPFTableCell cell12=row1.createCell();
        XWPFRun run12=cell12.getParagraphs().get(0).createRun();
        run12.setText("任课教师");
            //第四列
        XWPFTableCell cell13=row1.createCell();
        XWPFRun run13=cell13.getParagraphs().get(0).createRun();
        run13.setText("xxx");

POI操作word表格,添加单元格,单元格对齐方法(不必合并单元格)_第1张图片

其实解决方式也很简单,只需要给每个单元格设置宽度所占百分比即可

cell00.setWidth("100%");
cell10.setWidth("25%");
cell11.setWidth("25%");
cell12.setWidth("25%");
cell13.setWidth("25%");

POI操作word表格,添加单元格,单元格对齐方法(不必合并单元格)_第2张图片

完美解决,这样一来我们还能够避免使用合并单元格这样的复杂操作来添加单元格。直接添加单元格即可。

你可能感兴趣的:(poi,word,java)