Example of uploading and reading Excel files in ASP. NET

Source: Internet
Author: User

In CSDN, someone often asks how to open an Excel database file. This article uses a simple example to read Excel data files.

First, create a Web application project and add a DataGrid Control, a file control, and a button control to the Web page.
Copy codeThe Code is as follows:
<INPUT id = "File1" type = "file" name = "File1" runat = "server">
<Asp: Button id = "Button1" runat = "server" Text = "Button"> </asp: Button>
<Asp: DataGrid id = "DataGrid1" runat = "server"> </asp: DataGrid>

In the Code view, first import the OleDb namespace:
Using System. Data. OleDb;

Enter the following code in the button clicking event:
Copy codeThe Code is as follows:
String strPath = "c: // test //" + DateTime. Now. ToString ("yyyyMMddhhmmss") + ". xls ";

File1.PostedFile. SaveAs (strPath );

String mystring = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = '" + strPath + "'; Extended Properties = Excel 8.0 ";

OleDbConnection cnnxls = new OleDbConnection (mystring );

OleDbDataAdapter myDa = new OleDbDataAdapter ("select * from [Sheet1 $]", cnnxls );

DataSet myDs = new DataSet ();

MyDa. Fill (myDs );

DataGrid1.DataSource = myDs. Tables [0];

DataGrid1.DataBind ();

C:/test must have the read and write permissions on the ASPNET user.

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.