我使用了Apache POI将TableViewer的内容转储到Excel工作簿中,并取得了良好的结果。
这里有一个示例方法,它创建了一个XSSFWorkbook,其中包含给定TableViewer的内容。它包含了单元格样式和自动调整列宽的示例。
请注意,我的列名存储在一个名为tableColumnNames的字符串数组中,因为它们在我的代码中的其他地方也被使用,并且只需使用该数组即可方便地使用,但您也可以从TableViewer中获取这些列名。
private XSSFWorkbook createWorkbookFromTable(TableViewer table) {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("My Table Data");
XSSFCellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
headerStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
headerStyle.setBorderTop(CellStyle.BORDER_THIN);
headerStyle.setBorderBottom(CellStyle.BORDER_THIN);
headerStyle.setBorderLeft(CellStyle.BORDER_THIN);
headerStyle.setBorderRight(CellStyle.BORDER_THIN);
headerStyle.setAlignment(HorizontalAlignment.CENTER);
Table table = table.getTable();
TableColumn[] columns = table.getColumns();
int rowIndex = 0;
int cellIndex = 0;
XSSFRow header = sheet.createRow((short) rowIndex++);
for (TableColumn column : columns) {
String columnName = column.getText();
XSSFCell cell = header.createCell(cellIndex++);
cell.setCellValue(column.getText());
cell.setCellStyle(headerStyle);
}
TableItem[] items = table.getTable().getItems();
for (TableItem item : items) {
XSSFRow row = sheet.createRow((short) rowIndex++);
cellIndex = 0;
for (int i = 0; i < columns.length; i++) {
String columnName = tableColumnNames[i];
XSSFCell cell = row.createCell(cellIndex++);
XSSFCellStyle cellStyle = wb.createCellStyle();
ha = HorizontalAlignment.RIGHT;
cellStyle.setAlignment(ha);
cell.setCellStyle(cellStyle);
String text = item.getText(i);
cell.setCellValue(text);
}
}
for (int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn((short) i);
}
return wb;
}
一旦您获得了XSSFWorkbook,您可以像这样将其转储到文件中:
public void dumpWorkbookToAFile(XSSFWorkbook wb, String filename) {
try {
FileOutputStream fos = new FileOutputStream(filename);
wb.write(fos);
fos.close();
MessageDialog.openInformation(shell,
"Save Workbook Successful",
"Workbook saved to the file:\n\n" + filename);
} catch (IOException ioe) {
ioe.printStackTrace();
String msg = ioe.getMessage();
MessageDialog.openError(shell,
"Save Workbook Failed",
"Could not save workbook to the file:\n\n" + msg);
}
}