使用带保存对话框的java将内容导出到文本文件

时间:2012-09-26 09:29:38

标签: java servlets export-to-text

我有一个有一些值的结果集,我想用结果集将数据导出为带有保存对话框的文本文件。

如何在java中执行此操作?。

我已经完成了以上对excel和java的要求。

response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".xls\"");

response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".pdf\""); response.setContentType("application/pdf");

更新:

if(exportTo.equals("text")){
            response.setContentType("text/plain");
            response.setHeader("Content-disposition", "attachment; filename=\"" + reportName + ".txt\"");
            try {

            } catch (Exception e) {
                // TODO: handle exception
            }

        }

在此

在try块中如何设置从结果集到输出流的内容并使其可用。

1 个答案:

答案 0 :(得分:3)

唯一的区别是:

response.setContentType("text/plain");

您可以在此处查看完整示例(http://www.mkyong.com/servlet/servlet-code-to-download-text-file-from-website-java/

<强>更新

这是我开发和测试的一个演示,并且工作得很好:

public class ServletDownloadDemo extends HttpServlet {
    private static final int BYTES_DOWNLOAD = 1024;

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
                                                                                       IOException {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");

        String s = "Test\n\nText file contects!!";
        InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));

        int read = 0;
        byte[] bytes = new byte[BYTES_DOWNLOAD];
        OutputStream os = response.getOutputStream();

        while ((read = input.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        os.flush();
        os.close();
    }
}

下载名为downloadname.txt的文本文件,其内容为String s

更新2

    String s = "";
    while (rs.next()) {
        s += rs.getString("column_name");
    }

    if (exportTo.equals("text")) {
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment;filename=downloadname.txt");

        try {
            InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));

            int read = 0;
            byte[] bytes = new byte[BYTES_DOWNLOAD];
            OutputStream os = response.getOutputStream();

            //data form resultset

            while ((read = input.read(bytes)) != -1) {
                os.write(bytes, 0, read);
            }
            os.flush();
            os.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

您必须填充ResultSet并在String s中填写所需内容。 就是这样。