我正在做一个项目,我找不到一种方法可以下载从数据库中打印出表格的页面内容。我希望有一个按钮,让客户有机会以pdf或csv的形式下载表格的内容。这是的servlet
package bacit.web.bacit_web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet(name = "BookingHistorikk", value = "/BookingHistorikk")
public class GetBookingHistorikk extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
{
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try
{
Class.forName("org.mariadb.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mariadb:**********", "root", "pass");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from BOOKING");
out.println("<table style=text-align:center border=1 width=50% height=10% >");
out.println("<tr><th>Start Dato</th><th>Slutt Dato</th><th>Kommentar</th><th>Levert</th><th>Total Pris</th></tr>");
while (rs.next())
{
Date startDate = rs.getDate("StartDate");
Date endDate = rs.getDate("EndDate");
String cmnt = rs.getString("Cmnt");
Boolean isDelivered = rs.getBoolean("IsDelivered");
int totalPrice = rs.getInt("TotalPrice");
out.println("<tr><td>" + startDate + "</td><td>" + endDate + "</td><td>" + cmnt + "</td><td>" + isDelivered + "</td><td>" + totalPrice + "</td></tr>");
}
out.println("</table>");
out.println("</html></body>");
con.close();
}
catch (Exception e)
{
out.println("error");
}
}
}
这里需要做两件事。。。
- 创建CSV文件
- 在
HttpServletResponse
的帮助下发送给用户
您可以创建一个CSV文件,内容如下:
String getMyCsvFileAsString() {
StringBuilder sb = new StringBuilder();
sb.append("id");
sb.append(',');
sb.append("Name");
sb.append('n');
sb.append("1");
sb.append(',');
sb.append("Prashant Ghimire");
sb.append('n');
writer.write(sb.toString());
}
然后你可以把它附加到这样的请求上:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename="myCsvFile.csv"");
try
{
OutputStream outputStream = response.getOutputStream();
// Get CSV file as string
String outputResult = getMyCsvFileAsString();
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
}
catch(Exception e)
{
System.out.println(e.toString());
}
}