В apache poi много уроков, но у меня проблемы с созданием таблиц. Я пробую этот код:
public class CreateTable
{
public static void main(String[] args)throws Exception
{
//Blank Document
XWPFDocument document= new XWPFDocument();
//Write the Document in file system
FileOutputStream out = new FileOutputStream(
new File("create_table.docx"));
//create table
XWPFTable table = document.createTable();
//create first row
XWPFTableRow tableRowOne = table.getRow(0);
tableRowOne.getCell(0).setText("col one, row one");
tableRowOne.addNewTableCell().setText("col two, row one");
tableRowOne.addNewTableCell().setText("col three, row one");
//create second row
XWPFTableRow tableRowTwo = table.createRow();
tableRowTwo.getCell(0).setText("col one, row two");
tableRowTwo.getCell(1).setText("col two, row two");
tableRowTwo.getCell(2).setText("col three, row two");
//create third row
XWPFTableRow tableRowThree = table.createRow();
tableRowThree.getCell(0).setText("col one, row three");
tableRowThree.getCell(1).setText("col two, row three");
tableRowThree.getCell(2).setText("col three, row three");
document.write(out);
out.close();
System.out.println("create_table.docx written successully");
}
}
Но в либровском офисе таблица ubuntu имеет бесконечную ширину, и когда я загружаю ее в google doc, в этом документе ничего нет. Установка ширины таблицы не помогает. Что я делаю неправильно? Помоги пожалуйста ((
Вы можете установить ширину следующим образом:
XWPFDocument doc = new XWPFDocument();
XWPFTable table = doc.createTable(1,2);
table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(6000));
table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2000));
table.getRow(0).getCell(0).setText("1A");
table.getRow(0).getCell(1).setText("1B");
XWPFTableRow newrow = table.createRow();
newrow.getCell(0).setText("2A");
newrow.getCell(1).setText("2B");
Ваш код работает отлично!
XWPF предназначен для создания документов .docx
. Если вам нужно работать с .doc
вам придется использовать HWPF.
Также... Структура XML этих документов отличается. Возможно, возникшие проблемы с форматированием могут быть вызваны этим.