Excel Reader ASP.NET

Posted by user304429 on Stack Overflow See other posts from Stack Overflow or by user304429
Published on 2010-03-30T13:27:15Z Indexed on 2010/03/30 23:03 UTC
Read the original article Hit count: 423

Filed under:
|
|
|

I declared a DataGrid in a ASP.NET View and I'd like to generate some C# code to populate said DataGrid with an Excel spreadsheet (.xlsx). Here's the code I have:

<asp:DataGrid id="DataGrid1" runat="server"/>
        <script language="C#" runat="server">
            protected void Page_Load(object sender, EventArgs e)
            {
                string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\FileName.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
                // Create the connection object
                OleDbConnection oledbConn = new OleDbConnection(connString);
                try
                {
                    // Open connection
                    oledbConn.Open();

                    // Create OleDbCommand object and select data from worksheet Sheet1
                    OleDbCommand cmd = new OleDbCommand("SELECT * FROM [sheetname$]", oledbConn);

                    // Create new OleDbDataAdapter
                    OleDbDataAdapter oleda = new OleDbDataAdapter();

                    oleda.SelectCommand = cmd;

                    // Create a DataSet which will hold the data extracted from the worksheet.
                    DataSet ds = new DataSet();

                    // Fill the DataSet from the data extracted from the worksheet.
                    oleda.Fill(ds, "Something");

                    // Bind the data to the GridView
                    DataGrid1.DataSource = ds.Tables[0].DefaultView;
                    DataGrid1.DataBind();
                }
                catch
                {
                }
                finally
                {
                    // Close connection
                    oledbConn.Close();
                }
            }
        </script>

When I run the website, nothing really happens. What gives?

© Stack Overflow or respective owner

Related posts about excel

Related posts about c#