Asp.net HttpHandler exports an Excel file from a database table

Source: Internet
Author: User

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 );
        }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.