为什么下载的 excel 文件不包含任何数据?该文件是空的
Why downloaded excel file is not containg any data ? the file is empty
大家好,我已经创建了一个 Servlet 文件。它作为 excel 文件下载,但其中不包含任何数据,而代码是为在 excel 文件中写入数据而构建的。基本上我已经完成了这些步骤:-
1.从数据库访问数据
2.print 该数据到 excel 文件。
现在按照预期进行此工作,但现在在 excel 时下载文件。那个时候它是一个空白 excel 文件,该文件中不包含任何数据。为什么会这样 请阐明我刚刚开始学习 JAVA 和 SERVLET 对此真的很陌生。
package servletProject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ExcelFile")
public class CSVServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String emails = "xyz@gmail.com";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
FileWriter writer =null;
ResultSet rs=null;
Connection con=null;
PreparedStatement ps=null;
try {
String fileName = emails+"data.csv";
System.out.println(fileName);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
ConnectionClass cn = new ConnectionClass();
con = cn.connectDb();
System.out.println("fileName"+fileName);
writer = new FileWriter(fileName);
//Write the CSV file header
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
ps = con.prepareStatement("select firstName,email from employees");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("firstName"));
CSVUtils.writeLine(writer,Arrays.asList(rs.getString("firstName"),rs.getString("email")));
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try{ rs.close();ps.close();con.close();}catch (Exception e) {}
}
}
}
// DB connection File
public class ConnectionClass {
public Connection connectDb() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
}catch (Exception e) {
con=null;
}
if(con!=null)
System.out.println("connected");
else
System.out.println("not connected");
return con;
}
}
//CSVUtil Files
package servletProject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
// https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
// default customQuote is empty
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}
这是一个写入响应输出流的版本。
请注意,我将 'writer' 更改为 OutputStream 而不是 FileWriter,因为这是您从 response.getOutputStream().
获得的内容
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
OutputStream writer = response.getOutputStream();
:
//Write the CSV file header
//(no change from your code here.)
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
这需要您更改 CSVUtils class 以接受 OutputStream 而不是 Writer 对象,但这并没有太大区别...
public static void writeLine(OutputStream w, etc...) throws IOException {
:
sb.append("\n");
String str = sb.toString();
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
w.write(bytes);
}
我强烈建议使用 CSV 文件库,例如 http://opencsv.sourceforge.net/,因为它们提供了很多很棒的功能。
大家好,我已经创建了一个 Servlet 文件。它作为 excel 文件下载,但其中不包含任何数据,而代码是为在 excel 文件中写入数据而构建的。基本上我已经完成了这些步骤:- 1.从数据库访问数据 2.print 该数据到 excel 文件。 现在按照预期进行此工作,但现在在 excel 时下载文件。那个时候它是一个空白 excel 文件,该文件中不包含任何数据。为什么会这样 请阐明我刚刚开始学习 JAVA 和 SERVLET 对此真的很陌生。
package servletProject;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Arrays;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ExcelFile")
public class CSVServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String emails = "xyz@gmail.com";
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req, resp);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
FileWriter writer =null;
ResultSet rs=null;
Connection con=null;
PreparedStatement ps=null;
try {
String fileName = emails+"data.csv";
System.out.println(fileName);
ServletContext context = getServletContext();
String mimeType = context.getMimeType(fileName);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileName);
response.setHeader(headerKey, headerValue);
ConnectionClass cn = new ConnectionClass();
con = cn.connectDb();
System.out.println("fileName"+fileName);
writer = new FileWriter(fileName);
//Write the CSV file header
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
ps = con.prepareStatement("select firstName,email from employees");
rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("firstName"));
CSVUtils.writeLine(writer,Arrays.asList(rs.getString("firstName"),rs.getString("email")));
}
writer.flush();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
try{ rs.close();ps.close();con.close();}catch (Exception e) {}
}
}
}
// DB connection File
public class ConnectionClass {
public Connection connectDb() {
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/classicmodels","root","root");
}catch (Exception e) {
con=null;
}
if(con!=null)
System.out.println("connected");
else
System.out.println("not connected");
return con;
}
}
//CSVUtil Files
package servletProject;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
public class CSVUtils {
private static final char DEFAULT_SEPARATOR = ',';
public static void writeLine(Writer w, List<String> values) throws IOException {
writeLine(w, values, DEFAULT_SEPARATOR, ' ');
}
public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
writeLine(w, values, separators, ' ');
}
// https://tools.ietf.org/html/rfc4180
private static String followCVSformat(String value) {
String result = value;
if (result.contains("\"")) {
result = result.replace("\"", "\"\"");
}
return result;
}
public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
boolean first = true;
// default customQuote is empty
if (separators == ' ') {
separators = DEFAULT_SEPARATOR;
}
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (!first) {
sb.append(separators);
}
if (customQuote == ' ') {
sb.append(followCVSformat(value));
} else {
sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
}
first = false;
}
sb.append("\n");
w.append(sb.toString());
}
}
这是一个写入响应输出流的版本。 请注意,我将 'writer' 更改为 OutputStream 而不是 FileWriter,因为这是您从 response.getOutputStream().
获得的内容protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
OutputStream writer = response.getOutputStream();
:
//Write the CSV file header
//(no change from your code here.)
CSVUtils.writeLine(writer,Arrays.asList("NAME","email"));
这需要您更改 CSVUtils class 以接受 OutputStream 而不是 Writer 对象,但这并没有太大区别...
public static void writeLine(OutputStream w, etc...) throws IOException {
:
sb.append("\n");
String str = sb.toString();
byte[] bytes = str.getBytes(Charset.forName("UTF-8"));
w.write(bytes);
}
我强烈建议使用 CSV 文件库,例如 http://opencsv.sourceforge.net/,因为它们提供了很多很棒的功能。