如何将对象列表下载为Excel文件?

时间:2018-03-11 10:12:10

标签: java jsp

我正在使用JSP以表格格式显示网页中的对象列表。该网页包含用于过滤行的过滤器选项。显示的行应该可供用户下载为excel文件。

如何将对象列表转换为excel文件?

1 个答案:

答案 0 :(得分:1)

如果您正在尝试开发网络应用,那么您只需在模型/ pojo类中编写自己的csv方法,即Contact.java

 public String toCsv() {
     return id + ","+ firstName + "," + lastName + "," + email + "," +    contactNo + "," + addedDate + "," + modifiedDate + "," + status + "\r\n";
 }

然后你可以调用这个方法来下载所有的csv列表文件

 private void download(HttpServletResponse response) throws IOException{
    response.setHeader("Content-type","text/csv");
    response.setHeader("Content-Disposition","attachment; filename=file.csv");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires"," 0");
    PrintWriter out=response.getWriter();
    // contactDAO.getAll() being the list
    for(Contact c: contactDAO.getAll()){
        out.println(c.toCsv());
    }
}