나는 좋은 결과 Excel 통합 문서에 TableViewer의 내용을 덤프 아파치 POI를 사용했습니다.
다음은 주어진 TableViewer의 내용을 포함하는 XSSFWorkbook을 생성하는 샘플 메소드입니다. 셀 스타일 지정 및 열 너비 자동 조절의 예제가 포함되어 있습니다.
tableColumnNames라는 문자열 배열에 내 열 이름이 있습니다. 코드 내 다른 곳에서 사용되었으므로이 배열을 사용하는 것이 편리하지만 TableViewer에서도 그 열을 배치 할 수 있습니다.
private XSSFWorkbook createWorkbookFromTable(TableViewer table) {
// create a workbook
XSSFWorkbook wb = new XSSFWorkbook();
// add a worksheet
XSSFSheet sheet = wb.createSheet("My Table Data");
// shade the background of the header row
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);
// add header row
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);
}
// add data rows
TableItem[] items = table.getTable().getItems();
for (TableItem item : items) {
// create a new row
XSSFRow row = sheet.createRow((short) rowIndex++);
cellIndex = 0;
for (int i = 0; i < columns.length; i++) {
// create a new cell
String columnName = tableColumnNames[i];
XSSFCell cell = row.createCell(cellIndex++);
// set the horizontal alignment (default to RIGHT)
XSSFCellStyle cellStyle = wb.createCellStyle();
ha = HorizontalAlignment.RIGHT;
cellStyle.setAlignment(ha);
cell.setCellStyle(cellStyle);
// set the cell's value
String text = item.getText(i);
cell.setCellValue(text);
}
}
// autofit the columns
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);
}
}