Excel 2003 = literature.xls
Sheets: LineCards, Data, Brochures, and Tips
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
public partial class literature : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadGrid(0);
}
protected void grd_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
LoadGrid(e.NewPageIndex);
}
void LoadGrid(int LineCards)
{
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("literature\\literature.xls") + ";" +
"Extended Properties=Excel 8.0;";
// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);
// Open connection with the database.
objConn.Open();
// The code to follow uses a SQL SELECT command to display the data from the worksheet.
// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [LineCards$]", objConn);
// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;
// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();
// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");
// Bind data to DataGrid control.
grd.DataSource = objDataset1.Tables[0].DefaultView;
grd.PageIndex = LineCards;
grd.DataBind();
// Clean up objects.
objConn.Close();
}
}
You’re going to need to perform this code once for each file. Essentially, just create a function to take care of it, and just pass the function your connectionString (or whatever element of it changes). This assumes that all of the files you are querying have the correct data you are looking for.
Here is an example of the function, and how to call it.
And the function…. I assume your first function worked, so I am just re-using your code. If your original function worked for one grid, this code should work for any number.
UPDATE
function now takes the file path instead of the entire connection string.