如何在java中创建新的excel文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19700354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:30:29  来源:igfitidea点击:

How to create new excel document in java

javaapache-poistruts1

提问by user2930535

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:

在这里,我使用 poi-jar 从数据库导出数据以使其工作正常。但在这里我想要改变而不是创建手动路径。我想让它自动下载,而不需要像这样创建任何手动路径:

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

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();
ses.close();
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(0).setCellValue("Sl.No");
rowhead.createCell(1).setCellValue("Magazine Name");
rowhead.createCell(2).setCellValue("Volume No");
rowhead.createCell(3).setCellValue("Issue No");
rowhead.createCell(4).setCellValue("Cost");
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);
    row.createCell(0).setCellValue(l1.getSl_no());
    row.createCell(1).setCellValue(l1.getMagazinename());
    row.createCell(2).setCellValue(l1.getVolumeno());
    row.createCell(3).setCellValue(l1.getIssueno());
    row.createCell(4).setCellValue(l1.getCost());
    i++;
}
try {
    FileOutputStream fileOut = new FileOutputStream(filename);
    hwb.write(file);
    fileOut.close();
} catch (IOException ex) {
    Logger.getLogger(LibraryExportDAO.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Your excel file has been generated!");
return "success";
}

采纳答案by Lucky

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,

如果您在浏览器中生成 excel,只需根据 url 调用您想要生成 excel 文件的方法,并像这样设置响应属性,

  //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)
  response.setContentType("application/vnd.ms-excel");

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

WriterClass:

作家类:

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
                   worksheet.getWorkbook().write(outputStream);
                   // Flush the stream
                   outputStream.flush();
              } 
              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

在响应接收端,您将被提示在浏览器窗口中下载文件.. LINK

回答by user2560569

Instead of this code,

而不是这个代码,

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

Use,

用,

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

This will create a file in project folder.

这将在项目文件夹中创建一个文件。

Cheers ...... !

干杯……!

回答by Debabrata

You have to write the file to response

您必须将文件写入响应

   ByteArrayOutputStream bos = null;

                        try {
                            File file = new File(filename);
                            FileInputStream fis = new FileInputStream(file);
                            bos = new ByteArrayOutputStream();
                            if (fis != null) {
                                byte[] buf = new byte[(int) file.length()];
                                for (int num; (num = fis.read(buf)) != -1;) {
                                    bos.write(buf, 0, num);
                                }
                            }
                            byte[] bytes = bos.toByteArray();
                            response.setContentType("application/vnd.ms-excel");
                            final OutputStream fileOutputStream = response.getOutputStream();
                            fileOutputStream.write(bytes);
                            fileOutputStream.flush();
                            fileOutputStream.close();
                        } catch (Exception e) {
                        }