ASP. NET implements reading Excel content and displaying it on Web

  • 2020-12-22 17:37:01
  • OfStack

An example of ASP.NET is used to read Excel content and display it on Web. It is a very practical function and will be shared for your reference. Specific implementation methods are as follows:

Click the event code.cs code is as follows:


protected void Button1_Click(object sender, EventArgs e)
{
    string strPath = "d:/test.xls";
    string mystring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source = '" + strPath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
      //"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(); 
}

Note:

If you use the classic "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = '" + strPath + "'; Extended Properties=Excel 8.0" returns an error: the external table is not in the expected format

This is because: Microsoft.Jet.OLEDB.4.0 is the Microsoft Jet engine, which is suitable for the 2003 version (it has not been tested before 2003, so it is not known which version can be adapted downward), while in 2007, Microsoft modified the main file formats of its Access and Excel, and renamed them.accdb (Access 2007 database file) and.xlsx (Excel 2007 file). Thus not supported by the Microsoft Jet engine, but Microsoft was quick to come up with Microsoft Office 2007 Desktop Drivers: Data Connectivity Components.

Therefore, the solution is to change the data providers in the connection string to Microsoft. ACE. OLEDB. 12.0.


Related articles: