小编典典
这是您可以用来导出为CSV的类:
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(ArrayList 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 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 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,然后将其输出到浏览器…)。这样的事情会起作用:
但请注意,您必须使用web.xml 将servlet链接到 url :
UsersServlet
__package__.UsersServlet
UsersServlet
getCSV
编辑:写入磁盘而不是发送到浏览器
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(String fileName, ArrayList 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();
}
}
}
2020-06-08