Asp tutorial. net HttpHandler export an Excel file from the database tutorial table
1. Create the "export Excel" asp.net tutorial Web application file.
2. Copy the NPOI library file to the new "lib" directory, add references, and select 7. dll files.
3. Add a general handler named DownloadExcel1.ashx.
4. Set the UserDB. mdf field to UserName and Password.
5. Add the following to the Default. aspx file:
<Div>
<A href = "DownloadExcel1.ashx"> Download an Excel file </a>
</Div>
6. Add the following code to the DownloadExcel1.ashx. cs file:
Context. Response. ContentType = "application/x-excel ";
String filename = HttpUtility. UrlEncode ("user data .xls ");
Context. Response. AddHeader ("Content-Disposition", "attachment; filename =" + filename );
HSSFWorkbook workbook = new HSSFWorkbook ();
HSSFSheet sheet = workbook. CreateSheet ();
Using (SqlConnection conn = new SqlConnection (@ "Data Source =. SQLEXPRESS; AttachDBFilename = | DataDirectory | UserDB. mdf; Integrated Security = True; User Instance = True "))
{
Conn. Open ();
Using (IDbCommand cmd = conn. CreateCommand ())
{
Cmd. CommandText = "select * from T_Users ";
Using (IDataReader reader = cmd. ExecuteReader ())
{
Int rownum = 0;
While (reader. Read ())
{
String username = reader. GetString (reader. GetOrdinal ("UserName "));
String password = reader. GetString (reader. GetOrdinal ("Password "));
HSSFRow row = sheet. CreateRow (rownum );
Row. CreateCell (0, HSSFCell. CELL_TYPE_STRING). SetCellValue (username );
Row. CreateCell (1, HSSFCell. CELL_TYPE_STRING). SetCellValue (password );
Rownum ++;
}
}
}
}
Workbook. Write (context. Response. OutputStream );
}