这是您可以用来导出为CSV的类:
import java.io.FileWriter;import java.io.IOException;import User; public class GenerateCsv { private static void generateCsvFile(ArrayList<User> users) { String output = "Email, Namen"; 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();} } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)