0

Can't we download Excel file by creating a new Excel. without saving it in any location.Here is the code to create an excel in C:\new.xls. I have a scenario to download the data in Excel. How can i do that by saving that in downloads folder. Please suggest me.

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");

Map<String, Object[]> data = new HashMap<String, Object[]>();

data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});

Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
    Row row = sheet.createRow(rownum++);
    Object [] objArr = data.get(key);
    int cellnum = 0;
    for (Object obj : objArr) {
        Cell cell = row.createCell(cellnum++);
        if(obj instanceof Date) 
            cell.setCellValue((Date)obj);
        else if(obj instanceof Boolean)
            cell.setCellValue((Boolean)obj);
        else if(obj instanceof String)
            cell.setCellValue((String)obj);
        else if(obj instanceof Double)
            cell.setCellValue((Double)obj);
    }
}

try {
    FileOutputStream out = 
            new FileOutputStream(new File("C:\\new.xls"));
    workbook.write(out);
    out.close();
    System.out.println("Excel written successfully..");

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
Odaiah
  • 305
  • 3
  • 6
  • 1
    Be more specific. What kind of application do you have? What protocol do you use? Are we talking about a server building a file and a client downloading it from a web page? From Api point of view it is rather easy. Write the file to a `ByteArrayOutputStream` or something like this. But if you have the xls only in memory you still need a way to transport it to your client. For this you need to describe the scenario better. – Matthias Nov 25 '13 at 07:42
  • Hi Matthias, Yes, I need to build it in server side and need to download it from web page in Excel.I have a Download button on the web page and when clicked on that Excel file has to be downloaded with data. – Odaiah Nov 25 '13 at 07:49
  • 1
    Well and now you have two problems 1) generating the xls which you seem to have tackled already and 2) offer a file for download on your web page. Solution of course depends on the framework you are using. For Spring you can have a look here for example: http://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers – Matthias Nov 25 '13 at 07:55

0 Answers0