Aspose Demos > Java Components > Aspose.Cells for Java > Java > QuickStart > Data > Importing Data

Importing Data - Aspose.Cells

This online demo demonstrates the ability ofAspose.Cells for Java to import data from a variety of data sources to fill the worksheets.

Aspose.Cells component is a powerful component, which can be used to create a list of data from different data sources including Array, ArrayList, DataColumn, DataGrid, DataTable, DataView, Array having Formulas, DataReader, Object Array and Two Dimensional Array etc. In this demo, you are provided a drop down list and a command button to exercise the importing tasks. The drop down list includes the names of all the data sources. You may select a data source from it and click the button to generate a workbook having the related list of data based on data source. You can either open the resultant excel files into MS Excel or save directly to your disk to check the results.

ClickExecute to see how example uses the selected data source to import data into Excel worksheet.

JAVA

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

package com.aspose.cells.demos.Workbooks.Data;

import com.aspose.cells.*;
import com.aspose.cells.demos.Demo;

public class ImportingData extends BaseData
{
    public void execute()
    {
        try
        {
            CreateImportingData("ImportingData.xls");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

JAVA

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403

package com.aspose.cells.demos.Workbooks.Data;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Random;
import java.util.TimeZone;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;

import com.aspose.cells.*;
import com.aspose.cells.demos.Demo;
import javax.servlet.http.HttpServletRequest;
import javax.faces.context.FacesContext;

public abstract class BaseData extends Demo
{
/*
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException
   {
      String fileName = response.getOutputStream();
      try {
         String command = request.getParameter("_command");

         ServletContext sc = getServletContext();
         String db_url = DB_URL_P1 + sc.getRealPath(DB_URL_P2);
         String template_file_path = sc.getRealPath(TEMPLATE_FILE_PATH_PART);
         Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
         if(command.equals("ColumnChart")) {
            setResponseHeader(response, "ColumnChart.xls");
            CreateColumnChart(out);
         }else if(command.equals("LineChart")){
            setResponseHeader(response, "LineChart.xls");
            CreateLineChart(out);
         }else if(command.equals("StockChart")){
            setResponseHeader(response, "StockChart.xls");
            CreateStockChart(out);
         }else if(command.equals("PivotTable")){
            setResponseHeader(response, "PivotTable.xls");
            CreatePivotTable(out);
         }
      } catch(Exception x) {
         x.printStackTrace();

         // say sorry
         response.setContentType("text/html");
         PrintWriter writer = new PrintWriter(out);

         writer.println("<html>");
         writer.println("<head>");
         writer.println("<title>sorry</title>");
         writer.println("</head>");
         writer.println("<body>");
         writer.println("<h1>Sorry, the demo programme failed for some reason.</h1>");
         x.printStackTrace(writer);
         writer.println("</body>");
         writer.println("</html>");
         writer.close();
      }
   }
*/

    public void CreateAddingHyperlinks(String fileName) throws IOException
   {
          Workbook workbook = new Workbook();
      Worksheets worksheets = workbook.getWorksheets();
      Worksheet worksheet = worksheets.getSheet(0);

      Cells cells = worksheet.getCells();
      Cell cell;
      /*  Adding link to a URL  */
      //Put a value into a cell
      cell = cells.getCell("A1");
      cell.setValue("Visit Aspose");
      Style style = cell.getStyle();
      Font font = new Font();
      font.setColor(Color.BLUE);
      font.setUnderline(Font.UNDERLINE_SINGLE);
      style.setFont(font);
      cell.setStyle(style);

      //Add a hyperlink to a URL at "A1" cell
      worksheet.getHyperlinks().add("A1", "B1", "http://www.aspose.com", "Hello Aspose", "1");

      /*Adding a link to an external file*/
      //Put a value into a cell
      cell = cells.getCell("A5");
      cell.setValue("SmartMarkerDesigner.xls");
     FacesContext context = FacesContext.getCurrentInstance();
     HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

      String template_file_path = getFileName(request,"/WEB-INF/Designer/SmartMarkerDesigner.xls");

      //Add a hyperlink to a URL at "B2" cell
      worksheet.getHyperlinks().add(4, 0, 4, 1, template_file_path, "Excel File", "1");

        
        HttpServletResponse response= (HttpServletResponse)context.getExternalContext().getResponse();
        workbook.protectFile(ProtectionType.MODIFY_FILE,"aspose");
        response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "inline; filename=test.xls");
            OutputStream out = response.getOutputStream();
                workbook.save(out);
        // setResponse(fileName, workbook);
   }
    public void CreateCalculateFormula(String template_file_path, String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        workbook.open(template_file_path);
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);
        Cells cells = worksheet.getCells();
        Cell cell;
        String strFormula;

        for (int i = 7; i <= 131; i++)
        {
            cell = cells.getCell(i, 2);
            strFormula = cell.getStringValue();
            cell = cells.getCell(i, 3);
            cell.setFormula(strFormula);
        }

        workbook.calculateFormula();
        for (int j = 7; j <= 131; j++)
        {
            cell = cells.getCell(j, 3);
            cells.getCell(j, 4).setValue(cell.getValue());
        }

        setResponse(fileName, workbook);
    }
    public void CreateDataFilter(String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);

        Cells cells = worksheet.getCells();
        Cell cell;
        //Put a value into a cell
        cell = cells.getCell("A1");
        cell.setValue("Fruit");
        cell = cells.getCell("B1");
        cell.setValue("Total");
        cell = cells.getCell("A2");
        cell.setValue("Apple");
        cell = cells.getCell("B2");
        cell.setValue(1000);
        cell = cells.getCell("A3");
        cell.setValue("Orange");
        cell = cells.getCell("B3");
        cell.setValue(2500);
        cell = cells.getCell("A4");
        cell.setValue("Bananas");
        cell = cells.getCell("B4");
        cell.setValue(2500);
        cell = cells.getCell("A5");
        cell.setValue("Pear");
        cell = cells.getCell("B5");
        cell.setValue(1000);
        cell = cells.getCell("A6");
        cell.setValue("Grape");
        cell = cells.getCell("B6");
        cell.setValue(2000);

        cell = cells.getCell("D1");
        cell.setValue("Count:");
        cell = cells.getCell("E1");
        cell.setFormula("=SUBTOTAL(2, B1:B6)");

        CellArea cellArea = new CellArea("A1", "B6");
        worksheet.getAutoFilter().setRange(cellArea);

        setResponse(fileName, workbook);
    }
    public void CreateDataValidation(String template_file_path, String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        workbook.open(template_file_path);
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);

        Cells cells = worksheet.getCells();
        Validations validations = worksheet.getValidations();
        Cell cell;
        cell = cells.getCell("A1");
        cell.setValue("Enter Number:");
        cell = cells.getCell("B1");
        cell.setValue(100);
        //Create a validation object
        int index = validations.add();
        Validation validation = validations.get(index);
        //Set the validation type to whole number
        validation.setType(ValidationType.WHOLE_NUMBER);
        //Set the operator for validation to between
        validation.setOperator(OperatorType.BETWEEN);
        //Set the minimum value for the validation
        validation.setFormula1("0");
        //Set the maximum value for the validation
        validation.setFormula2("10");
        validation.setShowError(true);
        validation.setAlertType(ValidationAlertType.INFORMATION);
        validation.setErrorTitle("Error");
        validation.setErrorMessage("Enter value between 0 to 10");
        validation.setInputMessage("Data Validation using Condition for Numbers");
        validation.setIgnoreBlank(true);
        validation.setShowInput(true);
        validation.setShowError(true);

        //Apply the validation to a range of cells from B1 to B1 using the CellArea structure
        CellArea cellArea = new CellArea();
        cellArea.setStartRow(0);
        cellArea.setEndRow(0);
        cellArea.setStartColumn(1);
        cellArea.setEndColumn(1);

        //Add the cell area to Validation
        validation.getAreaList().add(cellArea);

        setResponse(fileName, workbook);
    }
    public void CreateHelloWorld(String template_file_path, String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        workbook.open(template_file_path);
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);
        Cells cells = worksheet.getCells();
        Cell cell;

        //Put a string value into the cell using its name
        cell = cells.getCell("A1");
        cell.setValue("Cell Value");

        //put a string value into the cell using its name
        cell = cells.getCell("A2");
        cell.setValue("Hello World");

        //Put an boolean value into the cell using its name
        cell = cells.getCell("A3");
        cell.setValue(true);

        //Put an int value into the cell using its name
        cell = cells.getCell("A4");
        cell.setValue(100);

        //Put an double value into the cell using its name
        cell = cells.getCell("A5");
        cell.setValue(2856.5);

        //Put an object value into the cell using its name
        Object obj = "Aspose";
        cell = cells.getCell("A6");
        cell.setValue(obj);

        //Put an datetime value into the cell
        Calendar calendar = Calendar.getInstance();
        cell = cells.getCell("A7");
        cell.setValue(calendar);
        Style style = cell.getStyle();
        style.setNumber(14);
        cell.setStyle(style);

        //Put a string value into the cell using its row and column
        cell = cells.getCell(0, 1);
        cell.setValue("Cell Value Type");
        int temp;
        for (int i = 1; i < 7; i++)
        {
            temp = cells.getCell(i, 0).getValueType();
            cell = cells.getCell(i, 1);
            switch (temp)
            {
                case CellValueType.NULL:
                    cell.setValue("Null");
                    break;
                case CellValueType.BOOLEAN:
                    cell.setValue("Boolean");
                    break;
                case CellValueType.DATETIME:
                    cell.setValue("Calendar");
                    break;
                case CellValueType.STRING:
                    cell.setValue("String");
                    break;
                case CellValueType.INT:
                    cell.setValue("Integer");
                    break;
                case CellValueType.DOUBLE:
                    cell.setValue("Double");
                    break;
                case CellValueType.RICH_TEXT_STRING:
                    cell.setValue("String");
                    break;
            }
        }
        
        setResponse(fileName, workbook);
        
    }
    public void CreateImportingData(String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);
        Cells cells = worksheet.getCells();
        String[] names = new String[] { "Tom", "John", "kelly" };
        cells.importArray(names, 0, 0, true);

        setResponse(fileName, workbook);
    }
    public void CreateNamedRange(String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);

        Cells cells = worksheet.getCells();
        Cell cell;

        //Create a named range and Set the name of the named range
        NamedRange nameRange = cells.createNamedRange("TestRange", "B1", "E5");
        //Accessing a specific Named Range
        NamedRange mynameRange = worksheets.getRangeByName("TestRange");
        cell = mynameRange.getCell(0, 0);
        cell.setValue("First");

        //Accessing All Named Ranges in a Worksheet
        NamedRange[] nameRangeList = worksheets.getNamedRanges();
        NamedRange testNameRange;
        for (int i = 0; i < nameRangeList.length; i++)
        {
            testNameRange = nameRangeList[i];
            cell = testNameRange.getCell(1, 0);
            cell.setValue("Second");
        }
        //Use cells.CreateRange method to extend it
        nameRange = cells.createNamedRange("TestRange", 0, 0, 6, 6);
        //access the address (row and column) of the range
        mynameRange = worksheets.getRangeByName("TestRange");
        int startRow = mynameRange.getStartRow();
        int endRow = mynameRange.getEndRow();
        int startColumn = mynameRange.getStartColumn();
        int endColumn = mynameRange.getEndColumn();

        setResponse(fileName, workbook);
    }
    public void CreateSetFormula(String template_file_path, String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        workbook.open(template_file_path);
        Worksheets worksheets = workbook.getWorksheets();
        Worksheet worksheet = worksheets.getSheet(0);

        Cells cells = worksheet.getCells();
        Cell cell;

        String strFormula = "";
        for (int i = 18; i <= 133; i++)
        {
            strFormula = cells.getCell(i, 2).getStringValue();
            cell = cells.getCell(i, 3);
            //Set a formula of the Cell
            cell.setFormula(strFormula);
        }

        setResponse(fileName, workbook);
    }
    public void CreateDataSorting(String template_file_path, String fileName) throws IOException
    {
        Workbook workbook = new Workbook();
        
        workbook.open(template_file_path);
        
        //Get the workbook datasorter object.
        DataSorter sorter = workbook.getDataSorter();

        //Set the first order for datasorter object.
        sorter.setOrder1(SortOrderType.DESCENDING);

        //Define the first key.
        sorter.setKey1(0);

        //Set the second order for datasorter object.
        sorter.setOrder2(SortOrderType.ASCENDING);

        //Define the second key.
        sorter.setKey2(1);

        //Sort data in the specified data range (CellArea range: A1:B14)
        sorter.sort(workbook.getWorksheets().getSheet(0).getCells(),new CellArea("A1","B14"));

        setResponse(fileName, workbook);
    }
}

JAVA

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

//////////////////////////////////////////////////////////////////////////
// Copyright 2008 Aspose Pty Ltd. All Rights Reserved.
//
// This file is part of Aspose Demos for Java. The source code in this file
// is only intended as a supplement to the documentation, and is provided
// "as is", without warranty of any kind, either expressed or implied.
//////////////////////////////////////////////////////////////////////////
package com.aspose.cells.demos;

import java.io.*;
import java.net.URL;
import java.sql.*;

import com.aspose.cells.Workbook;
import com.aspose.cells.WorkbookDesigner;
import com.aspose.cells.License;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.faces.context.FacesContext;

///////////////////////
import java.text.SimpleDateFormat;
import com.icesoft.faces.context.ByteArrayResource;
import com.icesoft.faces.context.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Locale;
import java.lang.reflect.*;

/**
 * Base class for Aspose.Cells.Demos classes that execute specific demos.
 */
public abstract class Demo
{
   private static final String DB_URL_P1 = "jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ=";
   private static final String DB_URL_P2 = "/WEB-INF/Database/Northwind.mdb";

   protected String TEMPLATE_FILE_PATH_PART = "/WEB-INF/Designer/Northwind.xls";
   protected Connection connection = null;

   public Demo() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

        // TODO: Consider using streams
        try {
            TEMPLATE_FILE_PATH_PART = getFileName(request, TEMPLATE_FILE_PATH_PART);
            initLicense(new License());
        }catch(Exception e) {
            e.printStackTrace();
        }
   }

    /**
     * Utility function that creates a connection to the Database.
     */
    private Connection createConnection()
    {
        try 
        {
            if (null!=connection) return connection;

            // Get absolute path
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

            String dbName = request.getRealPath(DB_URL_P2).replace("\\", "/");
            //System.out.println("db: " + dbName);

            //Load a DB driver that is used by the demos
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String connectionString = "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" + dbName;// + ";UID=Admin"
            connection = DriverManager.getConnection(connectionString, "", "");

            //Class.forName("net.sourceforge.jtds.jdbc.Driver");
            //String connectionString = "jdbc:jtds:sqlserver://localhost:1433/northwind";
            //connection = DriverManager.getConnection(connectionString, "northwind", "northwind");
        } catch (Exception e) {
            System.out.println("openDBConnection: " + e.toString());
        }

        return connection;
    }

    /**
     * Returns SQL dialect-specific date format (MS Access vs MS SQL Server)
     */
    protected static String getDate(Integer year, Integer month, Integer day) {
        return "#" + day.toString() + "/" + month.toString() + "/" + year.toString() + "#";

        //java.text.DecimalFormat nft = new java.text.DecimalFormat("00");
        //return "'" + year.toString() + "-" + nft.format(month) + "-" + nft.format(day) + "'";
    }

    /**
     * Returns SQL dialect-specific quarter formatting method
     */
    protected static String getQuarter(String fieldName) {
        return " FORMAT(" + fieldName +  ", 'yyyy/Q') ";
        //return " (convert(nvarchar(4), datepart(yyyy, " + fieldName + ")) + '/' + convert(nvarchar(4), datepart(qq, " + fieldName + "))) ";
    }

    /**
     * Returns SQL dialect-specific boolean formatting method
     */
    protected static String getBool(boolean flag) {
        return flag ? "Yes" : "No";
        //return flag ? "1" : "0";
    }

    /**
     * Returns SQL dialect-specific boolean formatting method
     */
    protected static String getDistinct() {
        return "DISTINCTROW";
        //return "DISTINCT";
    }

    /**
     * Utility function that creates a connection to the Database.
     */
    protected Statement createStatement()
    {
        return createStatement(true);
    }

    /**
     * Utility function that creates a connection to the Database.
     */
    protected Statement createStatement(boolean Scrollable)
    {
        try 
        {
            // Get absolute path
            Connection conn = createConnection();
            //if (Scrollable)
            //{
            //  return conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            //}else
            Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            //System.out.println("createStatement - returning: " + stmt);
            return stmt;

        } catch (Exception e) {
            System.out.println("createStatement: " + e.toString());
        }

        return null;
    }

    /**
     * Utility function that creates a connection to the Database.
     */
    protected PreparedStatement prepareStatement(String stmt)
    {
        try 
        {
            Connection conn = createConnection();
            PreparedStatement pstmt = conn.prepareStatement(stmt
            //ResultSet.TYPE_SCROLL_INSENSITIVE
                ,ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
            //System.out.println("prepareStatement - returning: " + pstmt);
            return pstmt;

        } catch (Exception e) {
            System.out.println("prepareStatement: " + e.toString());
        }

        return null;
    }

    protected void closeConnection() throws SQLException
    {
        if (null!=connection) {
             connection.close();
             connection = null;
        }
    }

    protected String getFileName(HttpServletRequest request, String absoluteName)
        throws java.io.FileNotFoundException
    {
        URL url = getClass().getClassLoader().getResource(absoluteName);
        if (null==url && null!=request)
        {
            String path =
                request.getRealPath(absoluteName).replace("\\", "/");

            //System.err.println("Failed to load " + absoluteName);
            //System.err.println("Loading file from " + path);

            return path;
        }

        String path = new File(url.getPath()).getAbsolutePath();
        //return url.toString();
        return path;
    }

    protected InputStream getFile(HttpServletRequest request, String absoluteName)
        throws java.io.FileNotFoundException
    {
        InputStream is = getClass().getClassLoader().getResourceAsStream(absoluteName);
        if (null==is && null!=request)
        {
            String path =
                request.getRealPath(absoluteName).replace("\\", "/");

            System.err.println("Failed to load " + absoluteName);
            System.err.println("Loading file from " + path);
            is = new FileInputStream(path);
        }

        return is;
    }

    /**
     * Executes the demo and returns a generated document. Implement in the derived classes.
     */
    public abstract void execute() throws Exception;

    protected final String FILE_NAME = "result.xls";

    public Resource getGeneratedfile() {
        byte[] res = getResult();
        if (null==res || res.length<1) {
            return null;
        }
        return new ByteArrayResource(res);
    }

    private String fileName = FILE_NAME;
    public String getFilename() {
        return fileName;
    }

    private String respType = "application/vnd.ms-excel";
    public String getResptype() {
        return respType;
    }
    public void setResptype(String v) {
        respType = v;
    }

    public void setFilename(String v) {

        // NOTE that demos like Pivot Table demo just don't work with such file names
        // so we don't use date(time) stamp for cells demos

        //SimpleDateFormat formatter = new SimpleDateFormat ("hh-mm-ss-", Locale.US);
        //String curDate = formatter.format(new Date());
        //this.fileName = curDate + v;
        this.fileName = v;

        //System.out.println("Response: " + this.fileName + " (" + v + ")");
    }

    public  byte[] getResult()
    {
        return resp;
    }

    protected void setResponse(String fName, ByteArrayOutputStream out) throws IOException {
        setFilename(fName);
        resp = out.toByteArray();
        out.close();
        // outputStream.write(this.response);
    }
    protected void setResponse(String fName,byte[] out) throws IOException {
        setFilename(fName);
        resp = out;

    }

    protected byte[] resp;

    protected void setResponse(String fileName, Workbook w) throws IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        w.save(out);
        setResponse(fileName, out);
    }

    protected void setResponse(String fileName, WorkbookDesigner w) throws IOException
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        w.save(out);
        setResponse(fileName, out);
    }

    /**
     *
     * Initializes license (if demo license is available).
     * you may insert your licensing code here that would use obj's
     * setLicense based on InputStream rather than passing it on
     * to 3rd-party class.
     *
     */
    public static void initLicense(Object obj) {
        try {

            Class myclass = Class.forName("com.aspose.demos.Common");
            if (null==myclass) {
                System.out.println("initLicense not found");
                return ;
            }

            //Use reflection to list methods and invoke them
            Method[] methods = myclass.getMethods();
            Object object = myclass.newInstance();

            Class partypes[] = new Class[1];
            partypes[0] = Object.class;
           
            Method meth = myclass.getMethod("initLicense", partypes);
            if (null!=meth) {

                    //System.out.println("Calling " + meth.getName());
                    Object arglist[] = new Object[1];
                    arglist[0] = obj;

                    meth.invoke(object, arglist);
            }
        } catch (ClassNotFoundException cnfe) {
            // Ignore
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

XHTML

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ice="http://www.icesoft.com/icefaces/component"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:c="http://java.sun.com/jstl/core"
      >

<ui:composition template="/WEB-INF/includes/templates/page-template.xhtml">
                        
    <ui:define name="pageTitle">
    Importing Data - Aspose.Cells Demos
  </ui:define>

    <ui:define name="page-content">
        <ui:decorate template="/WEB-INF/includes/templates/tabbed_container.xhtml">
            <ui:define name="example">
              <table width="90%" align="center" cellspacing="0" cellpadding="0" border="0">
                <tr>
        <td width="19" valign="top"><img src="/Common/images/heading_lft.jpg" alt="" width="19" height="41" /></td>
        <td width="100%" class="demos-heading-bg"><h2 class="demos-heading-bg"> <font face="Arial" size="4">&nbsp;Importing Data - Aspose.Cells</font></h2></td>
        <td width="19" valign="top"><img src="/Common/images/heading_rt.jpg" alt="" width="19" height="41" /></td>
      </tr>
    </table>
    <p class="componentDescriptionTxt"> <font face="Arial" size="2">This online demo demonstrates the ability of <a
href="http://www.aspose.com/categories/java-components/aspose.cells-for-java/default.aspx">Aspose.Cells</a> for Java to import data from a variety of data sources to fill the worksheets.</font></p>
    <p class="componentDescriptionTxt"> <font face="Arial" size="2">Aspose.Cells component is a powerful component, which can
      be used to create a list of data from different data sources including Array, ArrayList, DataColumn, DataGrid, DataTable, DataView, Array having Formulas, DataReader, Object Array
      and Two Dimensional Array etc. In this demo, you are provided a drop down list
      and a command button to exercise the importing tasks. The drop down list includes
      the names of all the data sources. You may select a data source from it and click
      the button to generate a workbook having the related list of data based on data
      source. You can either open the resultant excel files into MS Excel or save directly
      to your disk to check the results. </font> </p>
    <p class="componentDescriptionTxt">Click <b>Execute</b> to see how example uses the selected data source to import
      data into Excel worksheet.
      </p>
                <h:commandButton id="generate" action="#{dataimport.execute}" value="Execute" />

                <ice:outputResource id="outResource"
                    mimeType="application/vnd.ms-excel"
                    resource="#{dataimport.generatedfile}"
                    fileName="#{dataimport.filename}"
                    shared="false" />
            </ui:define>
        </ui:decorate>
    </ui:define>
        </ui:composition>
</html>