这是一个可用于导出到 CSV 的类:
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(ArrayList<User> users)
{
String output = "Email, Name\n";
for (User user in users) {
output += user.getEmail() + ", " + user.getName() + "\n";
}
return output;
}
}
以 MVC 方式工作
以下是您的代码应该如何编写:
假设您有一个名为的类。User.java里面有一个静态函数叫做get all users
public class User {
String name;
String email;
public static ArrayList<User> getAllUsers() {
// returns all users
...
}
}
然后假设您有一个名为 UsersServlet 的 servlet,它可以获取这些用户:
import javax.servlet.*;
import javax.servlet.http.*;
public class UsersServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/csv");
PrintWriter w = res.getWriter();
ArrayList<User> users = Users.getAllUsers();
w.prinln(GenerateCsv.generateCsvFile(users));
w.flush();
w.close();
}
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
...
}
}
例如,在您的 jsp 中,您将有一个调用 servlet 的简单锚标记(servlet 调用 User.java,获取数据,将它们形成为 CSV,然后将其输出到浏览器......)。像这样的东西会起作用:
<a href='/getCSV' > Export CSV </a>
但请注意,您必须使用 web.xml将 servlet 链接到url :
<web-app>
<servlet>
<servlet-name>UsersServlet</servlet-name>
<servlet-class>__package__.UsersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UsersServlet</servlet-name>
<url-pattern>getCSV</url-pattern>
</servlet-mapping>
</web-app>
编辑:写入磁盘而不是发送到浏览器
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(String fileName, ArrayList<User> users)
{
try
{
FileWriter writer = new FileWriter(fileName);
writer.append("Email");
writer.append(',');
writer.append("Name");
writer.append('\n');
for (User user in users) {
writer.append(user.getEmail());
writer.append(',');
writer.append(user.getName());
writer.append('\n');
}
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}