我想在SWT列上生成动态下拉列,以及excel表。
SWT同一表列以及excell列顺序相同。
答案 0 :(得分:0)
这是它的代码。 我已将SWT表转换为带有验证和受保护表格的Excel表。
SWTTableMain.java:-主类。
public class SWTTableMain extends Shell {
private Table table;
public static final String[] ITEMS = { "a1", "a2", "a3", "a4" };
public static void main(String args[]) {
try {
Display display = Display.getDefault();
SWTTableMain shell = new SWTTableMain(display);
// tableShell = display.getActiveShell();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public SWTTableMain(final Display display) {
super(display, SWT.SHELL_TRIM);
setLayout(new GridLayout(1, false));
Button btnOpenexcel = new Button(this, SWT.NONE);
btnOpenexcel.setText("OpenExcel");
table = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn tblclmnSrNo = new TableColumn(table, SWT.NONE);
tblclmnSrNo.setWidth(100);
tblclmnSrNo.setText("SR No:");
tblclmnSrNo.setMoveable(true);
TableColumn tblclmnName = new TableColumn(table, SWT.NONE);
tblclmnName.setWidth(138);
tblclmnName.setText("Name");
tblclmnName.setMoveable(true);
TableColumn tblclmnNewColumn = new TableColumn(table, SWT.NONE);
tblclmnNewColumn.setWidth(119);
tblclmnNewColumn.setText("Address");
tblclmnNewColumn.setMoveable(true);
TableColumn tblclmnEmail = new TableColumn(table, SWT.NONE);
tblclmnEmail.setWidth(122);
tblclmnEmail.setText("Email");
tblclmnEmail.setMoveable(true);
TableColumn tblclmnDropdown = new TableColumn(table, SWT.NONE);
tblclmnDropdown.setWidth(100);
tblclmnDropdown.setText("DropDown");
tblclmnDropdown.setMoveable(true);
// fill table data
TableItem item1 = new TableItem(table, SWT.NONE);
item1.setText(new String[] { "1", "Test1", "Ahemdabad", "xyz@gmail.com" });
TableEditor editor = new TableEditor(table);
CCombo combo = new CCombo(table, SWT.NONE);
combo.setText("Select");
combo.setItems(ITEMS);
editor.grabHorizontal = true;
editor.setEditor(combo, item1, 4);
// Write data to xls
btnOpenexcel.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
// TODO Auto-generated method stub
ExcelSheet.generateExcelSheet(table, ITEMS);
ExcelDialog excelDialog = new ExcelDialog(display.getActiveShell(), SWT.NONE);
excelDialog.open();
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
createContents();
}
protected void createContents() {
setText("SWT Application");
setSize(597, 300);
}
}
ExcelSheet.java
public class ExcelSheet {
private static String[] DropdownValue = null;
static DataValidation dataValidation = null;
static DataValidationConstraint constraint = null;
static DataValidationHelper validationHelper = null;
public static void generateExcelSheet(final Table table, String[] ITEMS) {
try {
// For file read
InputStream ExcelFileToRead = new FileInputStream("D:\\XLTest\\ExportedData.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
// add a worksheet
XSSFSheet sheet = wb.getSheetAt(0);
cleanSheet(sheet);
wb.lockStructure();// locak wrokbbok
validationHelper = new XSSFDataValidationHelper(sheet);
// shade the background of the header row
XSSFCellStyle headerStyle = wb.createCellStyle();
headerStyle.setFillForegroundColor(IndexedColors.LEMON_CHIFFON.getIndex());
// add header row
TableColumn[] columns = table.getColumns();
// add data rows
TableItem[] items = table.getItems();
int[] Colorder = table.getColumnOrder();
int rowIndex = 0;
int cellIndex = 0;
int DropDownColOrder = 0;
XSSFRow header = sheet.createRow((short) rowIndex++);
for(int i= 0;i< Colorder.length; i++)
{
XSSFCell cell = header.createCell(cellIndex++);
cell.setCellValue(columns[Colorder[i]].getText());
System.out.println("Heder Value:-"+columns[Colorder[i]].getText());
if(columns[Colorder[i]].getText().equals("DropDown")){
System.out.println("i:-"+i);
DropDownColOrder = i;
}
cell.setCellStyle(headerStyle);
}
DropdownValue = ITEMS;
constraint = validationHelper.createExplicitListConstraint(DropdownValue);
int lastRow = table.getItemCount();
CellRangeAddressList addressList = new CellRangeAddressList(1,lastRow, DropDownColOrder, DropDownColOrder);
dataValidation = validationHelper.createValidation(constraint,addressList);
dataValidation.setSuppressDropDownArrow(true);
sheet.addValidationData(dataValidation);
for (TableItem item : items) {
// create a new row
XSSFRow row = sheet.createRow((short) rowIndex++);
if(row != null)
{
cellIndex = 0;
for (int i = 0; i < columns.length; i++)
{
// create a new cell
XSSFCell cell = row.createCell(cellIndex);
// set the horizontal alignment (default to RIGHT)
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setLocked(true);
cell.setCellStyle(cellStyle);
cell.setCellValue(item.getText(Colorder[cellIndex]));
cellIndex++;
}
}
}
// autofit the columns
for (int i = 0; i < columns.length; i++) {
sheet.autoSizeColumn((short) i);
}
String filename = "D:\\XLTest\\ExportedData.xlsx";
FileOutputStream fos = new FileOutputStream(filename);
wb.write(fos);
fos.close();
MessageDialog.openInformation(new Shell(),"Save Workbook Successful","Workbook saved to the file:\n\n" + filename);
} catch (IOException ioe) {
ioe.printStackTrace();
String msg = ioe.getMessage();
MessageDialog.openError(new Shell(), "Save Workbook Failed","Could not save workbook to the file:\n\n" + msg);
}
}
public static boolean cleanSheet(XSSFSheet sheet) {
int numberOfRows = sheet.getPhysicalNumberOfRows();
if(numberOfRows > 0) {
sheet.getCTWorksheet().unsetDataValidations();
for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
if( sheet.getRow(i) != null) {
sheet.removeRow(sheet.getRow(i));
} else {
System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... skip line: " + i);
}
}
return true;
} else {
System.out.println("Info: clean sheet='" + sheet.getSheetName() + "' ... is empty");
}
return false;
}
}
ExcelDialog.java
public class ExcelDialog extends Dialog {
protected Object result,tabledata;
protected Shell shell;
private OleFrame oleframe = null;
private OleClientSite oleClientSite = null;
private String fileLocation = "D:\\XLTest\\ExportedData.xlsx";
public ExcelDialog(Shell parent, int style) {
super(parent, style);
setText("SWT Dialog");
}
public Object open() {
createContents();
shell.open();
shell.setMaximized(true);
shell.layout();
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return result;
}
private void openCurrentDataSheet() {
// TODO Auto-generated method stub
System.out.println("called");
oleframe = new OleFrame(shell, SWT.NONE);
oleframe.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
oleClientSite = new OleClientSite(oleframe, SWT.NONE, "Excel.Sheet",new File(fileLocation));
oleClientSite.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
}
private void createContents() {
shell = new Shell(getParent(), SWT.SHELL_TRIM | SWT.BORDER);
shell.setSize(450, 300);
shell.setText(getText());
shell.setLayout(new GridLayout(1, false));
openCurrentDataSheet();
Button btnSave = new Button(shell, SWT.NONE);
btnSave.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1));
btnSave.setText("Save");
btnSave.addSelectionListener(new SelectionListener() {
@Override
public void widgetSelected(SelectionEvent e) {
System.out.println("click event called");
// File is aleredy located or not
File xlsFile = new File(fileLocation);
boolean fileAvilable = xlsFile.exists();
System.out.println("fileAvilable:--"+fileAvilable);
if(fileAvilable == true)
{
boolean filedeleted = xlsFile.delete();
System.out.println("filedeleted:--"+filedeleted);
File finalFile = new File(fileLocation);
oleClientSite.save(finalFile, true);
oleClientSite.deactivateInPlaceClient();
shell.dispose();
System.out.println("file new Saved");
}
}
@Override
public void widgetDefaultSelected(SelectionEvent e) {
// TODO Auto-generated method stub
}
});
}
}