0

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?

2
  • 1
    Are you sure you're not getting an error? - you don't have any code within your catch block Commented Mar 30, 2010 at 13:33
  • To use finally in a try/catch/finally block you dont need to specify the catch block...so try/finally will suffice and hence if any errors occur they will bubble up... Commented Mar 30, 2010 at 13:36

1 Answer 1

3

The old JET driver does not yet support the XLSX format, only the BIFF (XLS) format.

You'll need somthing like this for your connection string:

 Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\FileName.xlsx;Extended Properties="Excel 12.0;HDR=Yes;IMEX=2"

You'll also need to download and install this on your web server:

http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.