Get first table with GetSchema - c#

I'm trying to get the first sheet of an Excel File:
try
{
string constring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filepath + ";Extended Properties=Excel 12.0;";
OleDbConnection conn = new OleDbConnection(constring);
conn.Open();
DataTable myTables = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
var myTableName = conn.GetSchema("Tables").Rows[0].Table;
string sqlquery = string.Format("SELECT * FROM [{0}]", myTableName);
OleDbDataAdapter da = new OleDbDataAdapter(sqlquery, conn);
da.Fill(dt);
MessageBox.Show(Convert.ToString(dt.Rows.Count));
return dt;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButton.OK,
MessageBoxImage.Error);
return dt;
}
What am I doing wrong?
EDIT:
The following error is show up:
The Microsoft Office Access database engine could not find the 'Tables' object.
This works with Visual Basic:
Try
Dim constring As String = "Provider=Microsoft.ACE.OLEDB.12.0;" &
"Data Source=" & filepath &
";Extended Properties=Excel 12.0;"
Dim conn As New OleDbConnection(constring)
conn.Open()
Dim myTables As DataTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
Dim myTableName = conn.GetSchema("Tables").Rows(0)("TABLE_NAME")
Dim sqlquery As String = String.Format("SELECT * FROM [{0}]", myTableName)
Dim da As New OleDbDataAdapter(sqlquery, conn)
da.Fill(dt)
conn.Close()
MsgBox(dt.Rows.Count)
Return dt
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Critical)
Return dt
End Try
I'm trying to replicate it with C#.
The error line seems to be this one:
var myTableName = conn.GetSchema("Tables").Rows[0].Table;
It tries to replicate the following line in VB code:
Dim myTableName = conn.GetSchema("Tables").Rows(0)("TABLE_NAME")

Here it is all put together. The # sign preceding the file path string take the string and does not use the \ as an escape. In the interpolated string we do want the escape character for the embedded double quotes. The using block ensures that your connection is closed and disposed. I displayed the result in a combo box.
private void opCode()
{
string filePath = #"C:\Users\xxx\Documents\Excel\TestImport.xlsx";
string conString = $"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {filePath} ; Extended Properties = \"Excel 12.0; HDR = YES;\"";
Debug.Print(conString);
DataTable dt;
using (OleDbConnection cn = new OleDbConnection(conString))
{
cn.Open();
dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
}
var exSheets = (from dRow in dt.AsEnumerable()
select dRow["TABLE_Name"]).ToArray();
cbo1.Items.AddRange(exSheets);
}
****NOTE: The Linq query does not necessarily return the sheets in
the order that appear in the workbook

Related

Unable to import excel to DB table in server

I am using the below code to import excel data into DB table. The code works fine in my local and when I move this code to server the import fails in between. Also I don't get any error messages and I get a message data saved successfully.
For Ex: The excel has 75,000 data's and only 13,500 records are getting inserted and the size of the excel file is 5 MB.
Any suggestions about the possible problems?
CS:
protected void btnImportData_Click(object sender, EventArgs e)
{
try
{
string strCS = string.Empty; ;
string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
string query = "";
lblError.Text = "";
string FileName = string.Empty;
FileName = Path.GetFileName(FileUploadExcel.PostedFile.FileName);
string Extension = Path.GetExtension(FileUploadExcel.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
string path = Path.GetFileName(Server.MapPath(FileUploadExcel.FileName));
System.IO.File.Delete(Server.MapPath(FolderPath) + path);
FileUploadExcel.SaveAs(Server.MapPath(FolderPath) + path);
string filePath = Server.MapPath(FolderPath) + path;
if (strFileType != String.Empty)
{
if (strFileType.Trim() == ".xls")
{
strCS = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
strCS = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please upload the correct file format')", true);
return;
}
try
{
OleDbConnection conn = new OleDbConnection(strCS);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = dt.Rows[0]["Table_Name"].ToString();
query = "SELECT * FROM [" + sheetname + "]";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (conn.State == ConnectionState.Open)
{
conn.Close();
conn = null;
}
string strSqlTable = "TABLENAME";
string sclearsql = "delete from " + strSqlTable;
SqlConnection sqlconn = new SqlConnection(strCon);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(strCS);
oledbconn.Open();
OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
oledbcmd.CommandTimeout = 120;
OleDbDataReader dReader = oledbcmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(strCon);
bulkCopy.DestinationTableName = strSqlTable;
bulkCopy.BulkCopyTimeout = 120;
bulkCopy.BatchSize = 1000;
bulkCopy.WriteToServer(dReader);
oledbconn.Close();
ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data saved successfully');window.location='Panel.aspx';", true);
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
}
}
catch (Exception ex)
{
lblError.Text = "Upload status: The file could not be uploaded due to following reasons.Please check: " + ex.Message;
}
}
Hi remove the data reader on you code which read the excel file twice and use the dataset to fill out your SQL table:
See below:
DataTable dtexcel = new DataTable();
using (OleDbConnection conn = new OleDbConnection(strCS))
{
conn.Open();
DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
//Looping a first Sheet of Xl File
DataRow schemaRow = schemaTable.Rows[0];
string sheet = schemaRow["TABLE_NAME"].ToString();
if (!sheet.EndsWith("_"))
{
string query = "SELECT * FROM [" + sheet + "]";
OleDbDataAdapter daexcel = new OleDbDataAdapter(query, conn);
dtexcel.Locale = CultureInfo.CurrentCulture;
daexcel.Fill(dtexcel);
}
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
}
using (SqlConnection sqlconn = new SqlConnection(strCon))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlconn))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = strSqlTable;
sqlconn.Open();
sqlBulkCopy.WriteToServer(dtexcel);
}
}
Have you tried using the dts wizard? it is a nice tool if you have a excel sheet with data.
you use it by opening the command prompt. windowsbutton + r, and the write cmd.
and from in here you write dtswizard
then a wizard opens in a new window where you can select the excel sheet that you want to insert. There is many tutorials on google.
Hope you can use this

When I try to import an Excel spreadsheet in SQL I get an error

Below is my code, any help will be greatly appreciated
:The Microsoft Office Access database engine could not find the object 'Breach'. Make sure the object exists and that you spell its name and the path name correctly.
public void importdatafromexcel(string excelfilepath)
{
string ssqltable = "Testing";
string myexceldataquery = "select [Case Owner],[Case Number],[Severity] from [Breach]";
try
{
string sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 12.0;";
string ssqlconnectionstring = "Persist Security Info=False;Integrated Security=true;Initial Catalog=0Breach;server= CHAUDAHARI-J1-W\\SQLEXPRESS";
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
oledbconn.Close();
}
catch (Exception ex)
{
txtProcessingStatus.Text = ex.Message;
}
}
select [Case Owner],[Case Number],[Severity] from [Breach]
Is there a worksheet named "Breach" in the Excel file you are opening? In your statement above, I believe [Breach] should be the name of the worksheet you are looking for in the Excel file you are opening.

Import Excel file data into Sql server using asp.net

I want to import excel file data in to SQL Server but this gives an error as shown below:
external table is not in the expected format xls
I am working on windows 8.1 OS and excel 2013. I am using the following code.
try
{
if (FlUploadcsv.HasFile)
{
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
ds = new DataSet();
objAdapter1.Fill(ds);
Dt = ds.Tables[0];
}
}
catch (Exception ex)
{
}
First you need to Replace Connection string :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;");
With this :
If you are use import for .xls then use below one :
OleDbConnection OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
If you are use import for .xlsx then use below one :
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
Try this blow one :
try
{
if (FlUploadcsv.HasFile)
{
OleDbConnection OleDbcon;
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dtExcelData = new DataTable();
string FileName = FlUploadcsv.FileName;
string filePath = "C:\\Users\\admin\\Desktop\\Sheet1.xlsx";
string path = filePath;// string.Concat(Server.MapPath("~/Document/" + FlUploadcsv.FileName));
FlUploadcsv.PostedFile.SaveAs(path);
if (Path.GetExtension(path) == ".xls")
{
OleDbcon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + "; Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"");
}
else if (Path.GetExtension(path) == ".xlsx")
{
OleDbcon = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
}
OleDbcon.Open();
cmd.Connection = OleDbcon;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
objAdapter1 = new OleDbDataAdapter(cmd);
objAdapter1.Fill(ds);
dtExcelData = ds.Tables[0];
string consString = "Your Sql Connection string";
/* You want insert into your sql database table using SqlBulkCopy. */
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "SqlDatabase Table name where you want insert data";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add(".xls/.xlsx Header column name(Id)", "Your database table column(IndexId)");
.
.
.
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
/* You want insert into your sql database table using SqlBulkCopy. */
}
}
catch (Exception ex)
{ }
Here is a similar way to do it:
string filename = System.IO.Path.GetFileName(FileUpload1.FileName);
if (FileUpload1.HasFile == true) {
string fp = System.IO.Path.GetDirectoryName(FileUpload1.FileName);
string full = "C:\\Users\\user\\Documents\\" + filename;
TextBox1.Text = full;
//FileUpload1.SaveAs(Server.MapPath("Files/" + filename))
try {
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=full;Extended Properties=Excel 8.0;HDR=YES;";
string cmdStr = "Select * from [Sheet1$]";
using (OleDbConnection oledbconn = new OleDbConnection(connStr)) {
using (OleDbCommand oledbcmd = new OleDbCommand(cmdStr, oledbconn)) {
oledbconn.Open();
OleDbDataAdapter oledbda = new OleDbDataAdapter(oledbcmd);
DataSet ds = new DataSet();
oledbda.Fill(ds);
//save to an SQL Database
oledbconn.Close();
}
}
} catch (Exception ex) {
TextBox2.Text = ex.ToString();
}
}

How to handle invalid characters in OleDb Excel import?

I am importing excel files to my application and sometimes worksheets column names have "$" sign in it. I receive this Exception:
System.Data.OleDb.OleDbException was unhandled
Message=''6um$'$' is not a valid name. Make sure that it does not include invalid characters or punctuation and that it is not too long.
In this sheet "6um$" is a column name.
This is my code:
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
OleDbDataAdapter cmd = new System.Data.OleDb.OleDbDataAdapter(
"select * from [" + worksheetName + "$]", con);
con.Open();
System.Data.DataSet excelDataSet = new DataSet();
cmd.Fill(excelDataSet);
con.Close();
Any ideas how to handle this situation?
Edit:
I thought the problem was having $ in column name. But turns out, The problem is having $ sign in worksheet name!
Ok, I figured out the solution:
For some reason, the worksheets that I renamed myself have extra $ sign (no idea why, there is no $ sign in the excel but OLEDB returns them with extra $ something like this '6um$'$'). I trim the first $ off and use this code to check is there is any extra $ sign still left:
char delimiterChars = '$';
string[] words = worksheetName.Split(delimiterChars);
worksheetName=words[0];
if (Directory.Exists(serverPath))
{
string FileExist = sp + "book1.xlsx"; ;
string Exten = Path.GetExtension(FileExist);
string g = "sheet1";
if (File.Exists(FileExist))
{
if (Exten == ".xlsx")
{
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FileExist + ";Extended Properties=Excel 12.0";
OleDbConnection oledbConn = new OleDbConnection(connString);
try
{
// Open connection
oledbConn.Open();
string query = String.Format("select * from [{0}$]", g);
// Create OleDbCommand object and select data from worksheet Sheet1
OleDbCommand cmd = new OleDbCommand(query, 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, "sheetdt");
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
LblSuccess.Text = ex.Message;
}
finally
{
// Close connection
oledbConn.Close();
}
}
}
}

Importing Any Excel Spreadsheet into a DataGridView - C#

I have a program that imports an excel spreadsheet into a datagridview. I have written the code as follows:
try
{
OleDbConnectionStringBuilder connStringBuilder = new OleDbConnectionStringBuilder();
connStringBuilder.DataSource = file;
connStringBuilder.Provider = "Microsoft.Jet.OLEDB.4.0";
connStringBuilder.Add("Extended Properties", "Excel 8.0;HDR=NO;IMEX1");
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
DbDataAdapter adapter = factory.CreateDataAdapter();
DbCommand selectCommand = factory.CreateCommand();
selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connStringBuilder.ConnectionString;
selectCommand.Connection = connection;
adapter.SelectCommand = selectCommand;
data = new DataSet();
adapter.Fill(data);
dataGridView1.DataSource = data.Tables[0].DefaultView;
}
catch (IOException)
{
}
The line "selectCommand.CommandText = "SELECT * FROM [All Carpets to Excel$]";" takes the data from the sheet with that name. I was wondering how I could get this program to open an excel document with any sheet name. One that I may not know.
You can get all the sheets' names like so..
public string[] GetExcelSheetNames(string excelFileName)
{
OleDbConnection con = null;
DataTable dt = null;
String conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFileName + ";Extended Properties=Excel 8.0;";
con= new OleDbConnection(conStr);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}

Categories

Resources