user2930535 user2930535 - 1 year ago 90
Java Question

How to create new excel document in java

Here I am using poi-jar to export data from database to excel it working fine . But here I want change instead of creating manual path. I wanted make that as to download automatically with out creating any manual path like this:

OutputStream file = new FileOutputStream(new File("D:\\venki1213.xls"));

And this is my code:

Session ses = HibernateUtil.getSessionFactory().openSession();
String query;
query = "from LibraryImportEntity ";
List<LibraryImportEntity> list = ses.createQuery(query).list();
System.out.println("list size" + list.size());
String filename = "D://ranjith//ranjith1213.xls";
OutputStream file = new FileOutputStream(new File("D:\\venki1213.xls"));
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(1).setCellValue("Magazine Name");
rowhead.createCell(2).setCellValue("Volume No");
rowhead.createCell(3).setCellValue("Issue No");
int i = 1;
for (LibraryImportEntity l1 : list) {
System.out.println("sl_no" + l1.getSl_no());
System.out.println("Magazinename" + l1.getMagazinename());
System.out.println("sl_no" + l1.getVolumeno());
System.out.println("sl_no" + l1.getCost());
HSSFRow row = sheet.createRow((short) i);
try {
FileOutputStream fileOut = new FileOutputStream(filename);
} catch (IOException ex) {
Logger.getLogger(LibraryExportDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Your excel file has been generated!");
return "success";

Answer Source

If you are generating the excel in a browser just call the method you want to generate the excel file based on a url and set the response properties like this,

  //1.Fill the data from db

  //2.Set the response properties
  String fileName = "Excel.xls";
  response.setHeader("Content-Disposition", "inline; filename=" + fileName);
  // Make sure to set the correct content type(the below content type is ok)

  //3.Write to the output stream
  Writer.write();//call write method of Writer class to write the data to o/p stream

Writer Class:

public class Writer {

     private static Logger logger = Logger.getLogger("service");
          * Writes the report to the output stream
         public static void write(HttpServletResponse response, HSSFSheet worksheet) {

          logger.debug("Writing excel data to the stream");
              try {
                   // Retrieve the output stream
                   ServletOutputStream outputStream = response.getOutputStream();
                   // Write to the output stream
                   // Flush the stream
              catch (Exception e) {
                  logger.error("Unable to write excel data to the output stream");

In the response receiving end you'll be prompted to download the file in the browser window.. LINK

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download