import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFTable;
+import org.apache.poi.xssf.usermodel.XSSFTableStyleInfo;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
-import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
/**
* Demonstrates how to create a simple table using Apache POI.
Workbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet) wb.createSheet();
- //Create
+ // Create
XSSFTable table = sheet.createTable();
- table.setDisplayName("Test");
- CTTable cttable = table.getCTTable();
+ table.setName("Test");
+ table.setDisplayName("Test_Table");
- //Style configurations
- CTTableStyleInfo style = cttable.addNewTableStyleInfo();
+ // For now, create the initial style in a low-level way
+ table.getCTTable().addNewTableStyleInfo();
+ table.getCTTable().getTableStyleInfo().setName("TableStyleMedium2");
+
+ // Style the table
+ XSSFTableStyleInfo style = (XSSFTableStyleInfo)table.getStyle();
style.setName("TableStyleMedium2");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
+ style.setFirstColumn(false);
+ style.setLastColumn(false);
+ style.setShowRowStripes(true);
+ style.setShowColumnStripes(true);
- //Set which area the table should be placed in
- AreaReference reference = new AreaReference(new CellReference(0, 0),
- new CellReference(2,2));
- cttable.setRef(reference.formatAsString());
- cttable.setId(1);
- cttable.setName("Test");
- cttable.setTotalsRowCount(1);
-
- CTTableColumns columns = cttable.addNewTableColumns();
- columns.setCount(3);
- CTTableColumn column;
+ // Set the values for the table
XSSFRow row;
XSSFCell cell;
for(int i=0; i<3; i++) {
- //Create column
- column = columns.addNewTableColumn();
- column.setName("Column");
- column.setId(i+1);
- //Create row
+ // Create row
row = sheet.createRow(i);
for(int j=0; j<3; j++) {
- //Create cell
+ // Create cell
cell = row.createCell(j);
if(i == 0) {
- cell.setCellValue("Column"+j);
+ cell.setCellValue("Column"+(j+1));
} else {
- cell.setCellValue("0");
+ cell.setCellValue((i+1)*(j+1));
}
}
}
+ // Create the columns
+ table.addColumn();
+ table.addColumn();
+ table.addColumn();
+ // Set which area the table should be placed in
+ AreaReference reference = new AreaReference(new CellReference(0, 0),
+ new CellReference(2,2));
+ table.setCellReferences(reference);
+
+ // Save
FileOutputStream fileOut = new FileOutputStream("ooxml-table.xlsx");
wb.write(fileOut);
fileOut.close();