Menu



Export data from database as csv file JSP Java


For upload file in JSP we using 2 files.

index.html

<!DOCTYPE html>
<html>
<body>
<a href="export.jsp" >Export data</a>
</body>
</html>

export.jsp

<%@ page import="java.io.*,java.sql.*"%>
<html>
<body>
<%
String filename = "c:\\csv\\csv_file.csv";
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "my_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
Statement stmt;
try
{
FileWriter fw = new FileWriter(filename);
fw.append("Id");
fw.append(',');
fw.append("First Name");
fw.append(',');
fw.append("Last Name");
fw.append(',');
fw.append("City Name");
fw.append('\n');
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select * from employee_details";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next())
{
fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append(',');
fw.append(rs.getString(4));
fw.append('\n');
}
fw.flush();
fw.close();
conn.close();
out.println("Successfully Created Csv file.");
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>