i have to upload a sheet into my database but the sheet names differ, i have seen an example on how to upload when sheet name is unknown, i see the sheet names are being found when i look at the complie but before it gets to bulkcopy into my database i get the error 'ExecuteReader requires an open and available Connection error' but my connection is open.
heres the code:
public void up(string sFileName = @"filename")
{
string ssqltable = "[dbo].[April]";
try
{
string sConStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES';", sFileName);
DataTable dt = new DataTable();
SqlConnection sqlconn = new SqlConnection(strConnString);
sqlconn.Open();
using (OleDbConnection connection = new OleDbConnection(sConStr))
{
connection.Open();
dt = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
var sheets = dt.Rows[0].Field<string>("TABLE_NAME");
foreach (var sheet in sheets) //loop through the collection of sheets ;)
{
//your logic here...
string myexceldataquery = string.Format("Select * FROM [{0}]; ", sheets);
//get data
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, connection);
OleDbDataReader dr = oledbcmd.ExecuteReader();
{
//sql bulk copy here!
DataTable table = new DataTable("benlist");
table.Load(dr);
// add two extra columns to data table to be added to database table [UPLOAD]
table.Columns.Add("Filename", typeof(string));
table.Columns.Add("User", typeof(string));
//set path
string CurrentFilePath = Path.GetFullPath(fuAttachment.PostedFile.FileName);
// add data to additional columns
foreach (DataRow row in table.Rows)
{
row["Filename"] = Path.GetFileNameWithoutExtension(CurrentFilePath);
row["User"] = Session["Username"].ToString();
}
Session["filename"] = Path.GetFileNameWithoutExtension(CurrentFilePath);
SqlBulkCopy bulkcopy = new SqlBulkCopy(strConnString);
bulkcopy.DestinationTableName = ssqltable;
////Mapping Table column
bulkcopy.ColumnMappings.Add("ParentId", "[ParentId]");
bulkcopy.ColumnMappings.Add("Date", "[Date]");
bulkcopy.ColumnMappings.Add("Caption", "[Caption]");
bulkcopy.ColumnMappings.Add("Filename", "Filename");
bulkcopy.ColumnMappings.Add("User", "User");
bulkcopy.WriteToServer(table);
connection.Close();
sqlconn.Close();
}
}
}
}
catch (Exception) { }
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('File Uploaded');", true);
}