java 用于将数据导出到 Excel 表格的不含 HTML 代码的 JSP 页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1755509/
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-10-29 17:50:20  来源:igfitidea点击:

JSP page without HTML code for exporting data to Excel Sheet

javajspservletscsv

提问by Ramesh

I am facing a problem in exporting my data to excel sheet, this is because of some code which other developers in my team made. So the main problem is to export the data to Excel or .cvs using JSP page but without using any HTML code. Any suggestion would also help me to explore in my developing arena. Thanks for your efforts.

我在将数据导出到 Excel 表时遇到问题,这是因为我团队中的其他开发人员编写了一些代码。所以主要的问题是使用JSP页面而不使用任何HTML代码将数据导出到Excel或.cvs。任何建议也将帮助我在我的发展领域进行探索。感谢您的努力。

回答by BalusC

Better use a Servlet for this. Raw Java code doesn't belong in a JSP file, that's simply recipe for maintenance trouble.

最好为此使用 Servlet。原始 Java 代码不属于 JSP 文件,这只是维护麻烦的秘诀。

To start, create a simple Java utility class which takes for example a List<List<T>>or a List<Data>(wherein Datarepresents one row) representing the CSV contents and an OutputStreamas method arguments and write logic which does the data copying task.

首先,创建一个简单的 Java 实用程序类,例如,它采用代表 CSV 内容的aList<List<T>>或 a List<Data>(其中Data代表一行)和一个OutputStreamas 方法参数和执行数据复制任务的编写逻辑。

Once you get that to work, create a Servlet class which takes some CSV file identifier as request parameter or pathinfo (I recommend using pathinfo as a certain webbrowser developed by a team in Redmond would fail on detection of filename/mimetype otherwise), uses the identifier to get the List<List<T>>or List<Data>from somewhere and writes it to the OutputStreamof the HttpServletResponsealong a set of correct response headers.

一旦你让它工作,创建一个 Servlet 类,它接受一些 CSV 文件标识符作为请求参数或路径信息(我建议使用路径信息,因为雷德蒙德的一个团队开发的某个网络浏览器会在检测文件名/mimetype 时失败),使用标识以获得List<List<T>>List<Data>从某处,并将其写入到OutputStreamHttpServletResponse沿设定正确的响应头。

Here's a basic kickoff example:

这是一个基本的启动示例:

public static <T> void writeCsv (List<List<T>> csv, char separator, OutputStream output) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, "UTF-8"));
    for (List<T> row : csv) {
        for (Iterator<T> iter = row.iterator(); iter.hasNext();) {
            String field = String.valueOf(iter.next()).replace("\"", "\"\"");
            if (field.indexOf(separator) > -1 || field.indexOf('"') > -1) {
                field = '"' + field + '"';
            }
            writer.append(field);
            if (iter.hasNext()) {
                writer.append(separator);
            }
        }
        writer.newLine();
    }
    writer.flush();
}

Here's an example how you could use it:

这是一个如何使用它的示例:

public static void main(String[] args) throws IOException {
    List<List<String>> csv = new ArrayList<List<String>>();
    csv.add(Arrays.asList("field1", "field2", "field3"));
    csv.add(Arrays.asList("field1,", "field2", "fie\"ld3"));
    csv.add(Arrays.asList("\"field1\"", ",field2,", ",\",\",\""));
    writeCsv(csv, ';', System.out);
}

And inside a Servlet you can basically do:

在 Servlet 中,您基本上可以执行以下操作:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String filename = request.getPathInfo();
    List<List<Object>> csv = someDAO().list();
    response.setHeader("content-type", "text/csv");
    response.setHeader("content-disposition", "attachment;filename=\"" + filename + "\"");
    writeCsv(csv, ',', response.getOutputStream());
}

Map this servlet on something like /csv/*and invoke it as something like http://example.com/context/csv/filename.csv. That's basically all. The filename in the pathinfo is important because a certain webbrowser developed by a team in Redmond ignores the filenamepart of the Content-Dispositionheader and uses the last path part of the URL instead.

将这个 servlet 映射到类似的/csv/*东西上,然后像http://example.com/context/csv/filename.csv. 这基本上就是全部。pathinfo 中的文件名很重要,因为 Redmond 的一个团队开发的某个 webbrowser 忽略filenameContent-Disposition标题部分,而是使用 URL 的最后一个路径部分。