Load an Excel spreadsheet file into a web page GridView

protected void Page_Load(object sender, System.EventArgs e)
{
 string ExcelFile = "C:\\ExcelSpreadsheetFile.xlsx";
 string ExcelConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFile + ";Extended Properties=\"Excel 12.0;HDR=YES;\"";
 System.Data.OleDb.OleDbConnection DataSource = new System.Data.OleDb.OleDbConnection(ExcelConnection);
 DataSource.Open();
 Data.DataTable ExcelTables = new Data.DataTable();
 ExcelTables = DataSource.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
 dynamic FirstSheetName = ExcelTables.Rows(0)("TABLE_NAME");
 Data.OleDb.OleDbDataAdapter DataAdapter1 = new Data.OleDb.OleDbDataAdapter("Select * from [" + FirstSheetName + "]", ExcelConnection);
 Data.DataTable DataTable1 = new Data.DataTable();
 DataAdapter1.Fill(DataTable1);
 DataAdapter1.Dispose();
 DataSource.Dispose();
 GridView1.DataSource = DataTable1;
 GridView1.DataBind();
}

No comments:

Post a Comment