我有一个结果集,它有一些值,我想使用保存对话框将结果集中的数据导出为文本文件。
如何在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 块中,如何将结果集中可用的内容设置为输出流并使其可用。
唯一的区别是:
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 = "TestnnText 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
中。就这样。