I have an excel file with one worksheet. I'm using MicroSoft.Office.Interop.Excel to read this file and then perform further execution.
Here is my code:
connString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strNewPath + ";Extended Properties=Excel 8.0;";
conn = new OleDbConnection(connString);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = null;
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
But, worksheet is not in the data table object.
Where you have mentioned the table(WorkSheet) name ??
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {null, null, null, "TABLE"});
//Get the First Sheet Name
string firstSheetName = schemaTable.Rows[0][2].ToString();
//Query String
string sql = string.Format("SELECT * FROM [{0}],firstSheetName);
Refer here MSDN
In case if you want to play around refer Reading Excel files from C#
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + "; Extended Properties=Excel 12.0;");
//After connecting to the Excel sheet here we are selecting the data
//using select statement from the Excel sheet
oconn.Open();
DataTable dbSchema = oconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1)
{
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string firstSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
string tbstrat = "M1000";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = oconn;
cmd.CommandText = "select * from [" + firstSheetName + "B8:" + tbstrat + "]";
OleDbDataAdapter adap = new OleDbDataAdapter();
DataTable dt = new DataTable();
adap.SelectCommand = cmd;
adap.Fill(dt);
oconn.Close();
Even you can try this
var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString);
var ds = new DataSet();
adapter.Fill(ds, "NameHere");
DataTable data = ds.Tables["NameHere"];
Related
I need to insert more than 1000 records into SQL Server. But using my code I am able to insert only 1000 records. Please help me.
using (SqlBulkCopy s = new SqlBulkCopy(dbConnection,SqlBulkCopyOptions.UseInternalTransaction, null))
{
s.DestinationTableName = TableName;
s.BatchSize = 10000;
s.BulkCopyTimeout = 1800;
foreach (var column in dt.Columns)
{
s.ColumnMappings.Add(column.ToString(), column.ToString());
}
s.WriteToServer(dt);
}
Below is the real time working code which i used in my project to insert the bulk data from excel to the SQL server
C# code:
public static DataSet Bindgrid_StoreInSQL(string path)
{
string strFileType = Path.GetExtension(path).ToLower();
string connString = "";
if (strFileType.Trim() == ".xls")
{
connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
string query = "SELECT * FROM [Sheet1$]";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable Exceldt = ds.Tables[0];
//creating object of SqlBulkCopy
SqlBulkCopy objbulk = new SqlBulkCopy(OneStopMethods_Common.constring_Property);
//assigning Destination table name
objbulk.DestinationTableName = "Tern_boq";
objbulk.ColumnMappings.Add("ID", "ID");
objbulk.ColumnMappings.Add("Bill_No", "Bill_No");
objbulk.ColumnMappings.Add("Page_No", "Page_No");
objbulk.ColumnMappings.Add("ItemNo", "ItemNo");
objbulk.ColumnMappings.Add("Description", "Description");
objbulk.ColumnMappings.Add("BOQ_Qty", "BOQ_Qty");
objbulk.ColumnMappings.Add("UNIT", "UNIT");
objbulk.ColumnMappings.Add("Category1", "Category1");
objbulk.ColumnMappings.Add("Category2", "Category2");
objbulk.ColumnMappings.Add("Category3", "Category3");
objbulk.ColumnMappings.Add("Estimated_UnitRate", "Estimated_UnitRate");
objbulk.ColumnMappings.Add("Estimated_Amount", "Estimated_Amount");
//inserting Datatable Records to DataBase
conn.Open();
objbulk.WriteToServer(Exceldt);
SqlDatabase obj = new SqlDatabase(OneStopMethods_Common.constring_Property);
string selquery = " select * from Tern_boq";
return obj.ExecuteDataSet(CommandType.Text, selquery);
}
Its works fine,Hope this can give you some idea,Please let me know your your thoughts or suggestions
I'm reading from xls/xlsx files to a DataSet.
string connstring;
if (currFileExtension == ".xlsx")
{
connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + currFilePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
}
else
{
connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + currFilePath + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
}
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //Get All Sheets Name
string firstSheetName = sheetsName.Rows[0][2].ToString(); //Get the First Sheet Name
string sql = string.Format("SELECT * FROM [{0}]", firstSheetName); //Query String
OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
DataSet set = new DataSet();
ada.Fill(set);
}
One of the columns is string and is getting cut after 255 characters.
How to set the column before I fill the DataSet?
Maybe it's a excel problem and I need to change the column in the excel?
You can add defined DataTable to DataSet.
Here's Code:
DataSet dataSet = new DataSet();
DataTable customTable = new DataTable();
DataColumn dcName = new DataColumn("Name", typeof(string));
dcName.MaxLength= 500;
customTable.Columns.Add(dcName);
dataSet.Tables.Add(customTable);
Am having one excel file with 2 different worksheets as fundmodelrate and project.Now I want to import these 2 different sheet values into 2 different sql tables(k2_fundmodelrate,k2_project).I can able to do import only if am working with 1 sheet and and 1 table,but I want two sheets values to be imported on two tables at the same time on button click event.
My code below:
private String strConnection = "Data Source=kuws4;Initial Catalog=jes;User ID=sa;Password=******";
protected void btnSend_Click(object sender, EventArgs e)
{
string path = fileuploadExcel.PostedFile.FileName;
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\fmr.xls;Extended Properties=Excel 12.0;Persist Security Info=False";
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("Select * from [FundModelRate$]", excelConnection);
//OleDbCommand cmd1 = new OleDbCommand("Select * from [FundModelRate$], [Project$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "K2_FundModelRate";
// sqlBulk.DestinationTableName = "K2_Project";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
I think the only way is to loop through your two sheets.
Have a look at This post. This will help you get the sheet names.
When you have the sheet names, you can then just loop through them and then load them into SQL.
Maybe this can help you:
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
string excelConnection = "";
if(strFile.Trim().EndsWith(".xlsx"))
{
excelConnection = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
}
else if(strFile.Trim().EndsWith(".xls"))
{
excelConnection = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
objConn = new OleDbConnection(excelConnection);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
for(int j=0; j < excelSheets.Length; j++)
{
OleDbCommand cmd = new OleDbCommand("Select * from " + excelSheets[j], excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "YourDestinationTableName";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
Note: Not tested
public void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "test_data";//sql table name
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if havedifferent
string myexceldataquery = "select * from [Sheet1$]";
try
{
//create our connection strings
string sexcelconnectionstring = #"provider=microsoft.jet.oledb.4.0;data source=" + excelfilepath + ";extended properties=" + "\"excel 8.0;hdr=yes;\"";
string ssqlconnectionstring = "server=ServerName;user id=sa;password=sa;database=Databasename;connection reset=false";
//execute a query to erase any previous data from our destination table
string sclearsql = "Delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
oledbconn.Close();
}
catch (Exception)
{
throw;
}
}
/*---------- call that file on buttonclick through OpenDialogBox--------*/
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
string strfilename = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
importdatafromexcel(strfilename);
}
Console.WriteLine(result);
MessageBox.Show("Exported to SQL successfully");
}
I am importing data from MS Excel.
The code i have written is,
var ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
uploadfile.PostedFile.FileName + ";" + "Extended Properties=Excel 12.0;";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
try
{
var objCmdSelect = new OleDbCommand("select * from [Sheet1$]", objConn);
}
and so on.
I got an error which looks very generic to me
The Microsoft Office Access database engine could not find the object 'Sheet1$'. Make sure the object exists and that you spell its name and the path name correctly
*
My worksheet name is spelled correclty
but for my confirmation, i did below code
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if(dt == null)
{
return null;
}
var excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach(DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
*
but i got my Data Table null.
My question is the connection is open successfully but i can't read data from the excel file.
Is there any special Authentication required.?
because i am getting the above error.
Instead if Ace.OLEDB you may try by Microsoft.Jet.OLEDB, because I faced the simillar then I switch over to Jet.OLEDB
string MyExelFile = "C:\Temp\Sample.xls";
string MyExcelSheet = "[Sheet1$]";
string StrConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + MyExelFile + ";
Extended Properties=\"Excel 8.0; HDR=Yes; IMEX=1\"";
String MySQLSelect = "select * from " + MyExcelSheet + "";
DataTable Items=new DataTable() ;
System.Data.OleDb.OleDbConnection Cn = new System.Data.OleDb.OleDbConnection();
Cn.ConnectionString = StrConn;
System.Data.OleDb.OleDbDataAdapter Da = new System.Data.OleDb.OleDbDataAdapter
(MySQLSelect, Cn);
Cn.Open();
Da.Fill(Items);
Cn.Close();
</pre>
When I try to open an Excel workbook I get a syntax error. Here is the code I'm using:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;"
+ "Data Source=" + fileName + ";"
+"Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";";
OleDbConnection objConn = new OleDbConnection(connectionString);
OleDbCommand objCommand = new OleDbCommand(#"SELECT * FROM Sheet1$", objConn);
OleDbDataAdapter odjAdp = new OleDbDataAdapter();
odjAdp.SelectCommand = objCommand;
DataTable dt1 = new DataTable();
odjAdp.Fill(dt1);
GridView2.DataSource = dt1;
GridView2.DataBind();
Why is this happening?
Because of the dollar symbol that sheet name needs to be escaped, enclose it in square brackets;
#"SELECT * FROM [Sheet1$]"