1. #1
    Ext User
    Join Date
    Nov 2008
    Posts
    75
    Vote Rating
    0
    jmhwhite2001 is on a distinguished road

      0  

    Default Code: Exporting Grid to Excel, PDF, etc.

    Code: Exporting Grid to Excel, PDF, etc.


    This post will only concentrate on exporting a grid data to excel (I use jExcelAPI). You can use this to export to pdf. I just wanted to share some example code with folks especially since many folks have helped me in the past.

    Essentially, here are the steps:
    1. Gather all your data (by default, only data that's visible in the grid is used - pagination)
    2. Send all your data to a servlet that creates the excel, pdf or other file.
    3. Return the filename from your servlet back to your GWT/GXT app.
    4. Open your file either by using GWT url redirect, but I actually call another servlet to send the file back and delete the file to save space.
    First, we need to add a hidden field to your panel that's used to send the filename to the servlet in #4.

    Code:
    final FormPanel formPanel = new FormPanel();
    final HiddenField hiddenVal = new HiddenField<String>();
    hiddenVal.setName("ExportedFilename");
     formPanel.add(hiddenVal);
    Now, here's the button code that I add to the grid's pagination toolbar.

    Code:
    // My grid
    protected EditorGrid<AircraftStatusBoardRow> editorGrid;
    // Column header is used to store the column header for the excel document
    final List<GridHeader> columnHeaders = new Vector();
    Button exportButton = new Button();
    exportButton.setIconStyle("export-icon");
    exportButton.setToolTip("Export table to Excel");
    
    exportButton.addSelectionListener(new SelectionListener() {
       @Override
                public void componentSelected(ComponentEvent ce) {
                    editorGrid.stopEditing();
                    final List<GridHeader> columnHeaders = new Vector();
                    for (int a = 0; a < editorGrid.getColumnModel()
                            .getColumnCount(); a++) {
                        columnHeaders.add(new GridHeader(editorGrid
                                .getColumnModel().getColumn(a).getHeader(),
                                editorGrid.getColumnModel().getColumn(a).getId()));
                    }
    
                   // Need to get all the grid data.  By default, whatever is on the page is used.
    
                    service.getAllGridData(new AsyncCallback() {
                        public void onFailure(Throwable caught) {
                            Dialog errorDialog = new Dialog();
                            errorDialog.setHeading("Error");
                            errorDialog.setButtons(Dialog.OK);
                            errorDialog.setBodyStyleName("pad-text");
                            errorDialog
                                    .addText("An error occurred exporting the table data: <p>"
                                            + caught.getMessage()
                                            + "<p>"
                                            + "Please contact your system administrator.");
                            errorDialog.setScrollMode(Scroll.AUTO);
                            errorDialog.setHideOnButtonClick(true);
                            errorDialog.show();
                        }
    
                        public void onSuccess(Object result) {
                            service.createExportExcelFile(
                                    (List<AircraftStatusBoardRow>) result,
                                    columnHeaders, new AsyncCallback() {
                                        public void onFailure(Throwable caught) {
                                            Dialog errorDialog = new Dialog();
                                            errorDialog.setHeading("Error");
                                            errorDialog.setButtons(Dialog.OK);
                                            errorDialog
                                                    .setBodyStyleName("pad-text");
                                            errorDialog
                                                    .addText("An error occurred exporting the table data: <p>"
                                                            + caught.getMessage()
                                                            + "<p>"
                                                            + "Please contact your system administrator.");
                                            errorDialog.setScrollMode(Scroll.AUTO);
                                            errorDialog.setHideOnButtonClick(true);
                                            errorDialog.show();
                                        }
    
                                        public void onSuccess(Object result) {
                                            String fileName = (String) result;
                                            hiddenVal.setValue(fileName);
    
                                            String url = GWT.getModuleBaseURL();
                                            url = url + "maintenanceplannerexport";
    
                                            formPanel.setAction(url);
                                            formPanel.submit();
                                        }
    
                                    });
                        }
    
                    });
                }
            });
    
            // customToolBar.add(exportButton);
            toolBar.insert(exportButton, 13);
    Here's the code to write out the excel file:

    Code:
    public String createExportExcelFile(List<AircraftStatusBoardRow> tableRecordData, List<GridHeader> columnHeader)
        throws MaintenancePlannerException {
            Date now = Calendar.getInstance().getTime();
            SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy");         
            String fileName = "ASBExport_" + df.format(now) + ".xls";
                    
            WritableWorkbook workbook;
            try {
                File exportFolder = new File("export");
                
                if (!exportFolder.exists()) {
                    exportFolder.mkdir();
                }
                            
                workbook = Workbook.createWorkbook(new File("export\\" + fileName));
                WritableSheet sheet = workbook.createSheet("Exported Data", 0);            
                createWorkSheet(sheet, columnHeader, tableRecordData);
                
                workbook.write();
                workbook.close();
            } catch (IOException e) {
                new LogServiceWrapper().log(LogLevel.SEVERE,
                        this.getClass().getName(), e.getMessage(), e);
                throw new MaintenancePlannerException(e);
            } catch (WriteException e) {
                new LogServiceWrapper().log(LogLevel.SEVERE,
                        this.getClass().getName(), e.getMessage(), e);
                throw new MaintenancePlannerException(e);
            } 
            
            return fileName;
        }
    
        private void createWorkSheet(WritableSheet sheet,
                List<GridHeader> columnHeader,
                List<AircraftStatusBoardRow> tableRecordData) throws WriteException {
            // Code left out.  Just reference jExcelAPI to write out data, it's very straightforward
        }
    Finally, here's the servlet code that reads in the filename and sends the excel file back to the client for open/save:

    Code:
    public class ExportServlet extends HttpServlet {
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            OutputStream out = null;
            File exportedFile = null;
            try {
                String fileName = request.getParameter("ExportedFilename");
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + fileName);
                
                exportedFile = new File("export\\" + fileName);
                
                
                Workbook book = Workbook.getWorkbook(exportedFile); 
                WritableWorkbook w = Workbook.createWorkbook(response
                        .getOutputStream(), book);           
                w.write();
                w.close();
            } catch (Exception e) {
                new LogServiceWrapper().log(LogLevel.SEVERE,
                        this.getClass().getName(), e.getMessage(), e);
                throw new ServletException("Exception in Excel Sample Servlet", e);
            } finally {
                if (out != null) {
                    out.close();
                }
                
                if (exportedFile != null) {
                    exportedFile.delete();
                }
                
            }
        }
    }
    I hope this helps!

  2. #2
    Ext User
    Join Date
    Nov 2008
    Posts
    75
    Vote Rating
    0
    jmhwhite2001 is on a distinguished road

      0  

    Default One more thing..

    One more thing..


    Forgot the GridHeader just in case folks wanted to know what it looks like:

    Code:
    public class GridHeader implements Serializable {
        private String headerName;
        private String headerID;
        
        public GridHeader() {
            super();
            this.headerID = "";
            this.headerName = "";
        }
        /**
         * @param headerName
         * @param headerID
         */
        public GridHeader(String headerName, String headerID) {
            super();
            this.headerName = headerName;
            this.headerID = headerID;
        }
        public String getHeaderName() {
            return headerName;
        }
        public void setHeaderName(String headerName) {
            this.headerName = headerName;
        }
        public String getHeaderID() {
            return headerID;
        }
        public void setHeaderID(String headerID) {
            this.headerID = headerID;
        }
    }

  3. #3
    Ext User
    Join Date
    Oct 2010
    Posts
    15
    Vote Rating
    0
    sebbalex is on a distinguished road

      0  

    Default


    Hi,
    I've used your template but I get an exception in the gxt formpanel:

    Code:
    00:51:04,155 [ERROR] Uncaught exception escaped
    java.lang.NullPointerException: null 	at com.extjs.gxt.ui.client.widget.form.FormPanel.submit(FormPanel.java:460) 	at com.italtel.client.patchfinder.GridWithPaging$6$1.onSuccess(GridWithPaging.java:266) 	at com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter.onResponseReceived(RequestCallbackAdapter.java:215) 	at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:287) 	at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:395) 	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 	at java.lang.reflect.Method.invoke(Method.java:597) 	at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) 	at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) 	at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:157) 	at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:326) 	at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:207) 	at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:126) 	at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:561) 	at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:269) 	at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91) 	at com.google.gwt.core.client.impl.Impl.apply(Impl.java) 	at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:214) 	at sun.reflect.GeneratedMethodAccessor165.invoke(Unknown Source) 	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 	at java.lang.reflect.Method.invoke(Method.java:597) 	at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103) 	at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71) 	at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:157) 	at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:281) 	at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:531) 	at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:352) 	at java.lang.Thread.run(Thread.java:619)
    this fail here:
    Code:
                        public void onSuccess(Object t) {
                            final FormPanel formPanel = new FormPanel();
                            formPanel.setMethod(FormPanel.METHOD_GET);
                            formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
                            formPanel.setAction(GWT.getModuleBaseURL() + "servicesWithoutDB/patchExportService");
                            final Hidden exportFilename = new Hidden();
                            exportFilename.setName("ExportedFilename");
                            formPanel.add(exportFilename);
                            String fileName = (String) t;
                            MessageBox.info("voi", "async correct " + GWT.getModuleBaseURL() + "servicesWithoutDB/patchExportService", null);
    
                            exportFilename.setValue(fileName);
                            formPanel.submit();
                        }
                    };
                    async().createExportExcelFile(store.getModels(), columnHeaders, ac);
                }
            });
    If I use the FormPanel of GWT everything goes fine.
    Do you have any idea?
    Thanks

  4. #4
    Sencha User
    Join Date
    Mar 2012
    Posts
    1
    Vote Rating
    0
    johnshilton is on a distinguished road

      0  

    Default


    Alternatively you can also use ClassicPDF editor, that can create, edit and convert pdf files. I hope you will be able to deal with your PDF file properly!

Thread Participants: 2

Turkiyenin en sevilen filmlerinin yer aldigi xnxx internet sitemiz olan ve porn sex tarzi bir site olan mobil porno izle sitemiz gercekten dillere destan bir durumda herkesin sevdigi bir site olarak tarihe gececege benziyor. Sitenin en belirgin ozelliklerinden birisi de Turkiyede gercekten kaliteli ve muntazam, duzenli porno izle siteleri olmamasidir. Bu yuzden iste. Ayrica en net goruntu kalitesine sahip adresinde yayinlanmaktadir. Mesela diğer sitelerimizden bahsedecek olursak, en iyi hd porno video arşivine sahip bir siteyiz. "The Best anal porn videos and slut anus, big asses movies set..."