How can I get list name from Excel? - c#

How can I get list name from Excel file? My actual script for read from Excel is this:
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name = "PP_s_vypocty"; // I actually using manualy name for read, but i want extract name from file.
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
string strCmd = "SELECT J38 FROM " + name;
OleDbCommand cmd = new OleDbCommand(strCmd, con);
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
UniqueValue.money.Add(double.Parse(da.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
I want to extract name from excel list without manually definition.

You can use OleDbConnection.GetSchema that return a datatable with the list of tables (excel worksheet in your case) that the database contains

Related

reading Excel spreadsheet in C#

I made a program to open Excel file.
There are exist data page and blank page.
Can I add only the pages where the data exists in the combo box?
Can I use ButtonEvent to view only pages that contain data?
string filePath = openFileDialog1.FileName;//파일 경로 가져오기
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
//string connectionString = string.Empty;
string sheetName = string.Empty;
using (OleDbConnection con = new OleDbConnection(ConnectStr()))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
public string ConnectStr()
{
string filePath = openFileDialog1.FileName;
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
string connectionString = string.Empty;
string sheetName = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03버전
connectionString = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07이상 버전
connectionString = string.Format(Excel16ConString, filePath);
break;
}
return connectionString;
}
I don't really get what is this. But I beg you need to show only specific sheet from spreadsheet correct me if i'm wrong.
There is a SQL commend that we can query from the specific sheet.
try
{
this.txtImportFilePath.Text = opd.FileName;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("Select * From [Sheet1$]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
trnxlistDataview.DataSource = dvEmp;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}

C# Import Excel Data to SQL Table

I am trying to use a method I pulled off of CodePlex, which exports data from Excel into a SQL table. I have made some minor code adjustments, but I still can't seem to get the data to import. Does anyone see anything glaringly wrong with my syntax? Thanks.
static void Main(string[] args)
{
importdatafromexcel("C:/Users/usname/Desktop/TestDirectories/FileSystemWatcher/Test_123.xlsx");
}
public static void importdatafromexcel(string excelfilepath)
{
//declare variables - edit these based on your particular situation
string ssqltable = "Name";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select Name,EmployeeID 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;\"";
//MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelfilepath + ";Extended Properties=Excel 8.0;HDR=YES'");
string ssqlconnectionstring = "server=DESKTOP-6CIMC97;Initial Catalog=TestDB;integrated security=true;connection reset = false";
//<add name="ProductContext" connectionString="Server=DESKTOP-6CIMC97; Initial Catalog=ProductApps; Integrated Security=True" providerName="System.Data.SqlClient" />
//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);
sqlcmd.Connection.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);
bulkcopy.DestinationTableName = ssqltable;
bulkcopy.WriteToServer(dr);
//while (dr.Read())
//{
// bulkcopy.WriteToServer(dr);
//}
oledbconn.Close();
}
catch (Exception ex)
{
//handle exception
}
}
The problem is here:
while (dr.Read())
{
bulkcopy.WriteToServer(dr);
}
The while (dr.Read()) block is useful if you are iterating over the results one-by-one.
But it's not you who is iterating over the results. You want the bulk copy operation to do the iterating.
Simply replace it with
bulkcopy.WriteToServer(dr);
This should work for you.
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
For more info, see the links below.
https://www.codeproject.com/tips/636719/import-ms-excel-data-to-sql-server-table-using-csh
http://www.c-sharpcorner.com/UploadFile/0c1bb2/inserting-excel-file-records-into-sql-server-database-using/
As you can tell, there are MANY ways to do what you want to do.

How to choose a value from cell in Excel

How can I choose correctly value from cell in Excel? I know that my problem is with command for select cell.
My actually scripts:
List<string> wsList = new List<string>();
DataTable schemaTable;
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name;
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
try
{
con.Open();
// Get schematable name from excel file
schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow row in schemaTable.Rows)
wsList.Add(row.Field<string>("TABLE_NAME"));
name = wsList[0];
// Select values from cell in excel
string strCmd = "SELECT J38 FROM [" + name + "]"; // I think that here is my main problem
// Command for select value
OleDbCommand cmd = new OleDbCommand(strCmd, con);
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
UniqueValue.money.Add(double.Parse(da.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
Image where you can watch what I need select: (Merged-Cell)
Debug:
For one or more required parameters were not found, no value
Merged cells and data adapters don't mix. If this is a one-off, copy the values from the original worksheet into an empty workbook and unmerge the cells, do any other cleanup manually. If this is a production process that needs to be repeated, and is high-volume, consider writing a VBA macro in the workbook to do the copypasta/cleanup process for you.

Import data from an Excel sheet into a SQL Server database

How to import the data from an Excel sheet into SQL Server database in asp net?
Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")
Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)
OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"
' Bulk Copy to SQL Server
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "customer1";
objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
objbulk.ColumnMappings.Add("City", "City");
objbulk.ColumnMappings.Add("Country", "Country");
objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
objbulk.WriteToServer(dt);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected DataTable DataExcel()
{
DataTable dt = new System.Data.DataTable();
try
{
string filenname=#"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
string ExcelConnectionString=#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
OleDbConn.Open();
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook),
OleDbConn);
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
sda.Fill(ds);
dt = ds.Tables[0];
OleDbConn.Close();
}
catch(Exception ex)
{
Response.Write(ex);
}
return dt;
}
}
}
Add a DataTable which can hold the Excel data generated via OLEDb.
string excelconnectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");
using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
{
using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
{
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
dtBulkUpload.Load(dr);
}
}
Then serialize this DataTable to XML which can be sent to SQL Stored Proc. This approach is very useful if there are too many fields and you can send all in a single parameter
using (StringWriter strXML = new StringWriter())
{
dtBulkUpload.TableName = "BulkUpload";
dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
xmlString = strXML.ToString();
}
using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
cmd.Parameters.AddWithValue("#dtBulkUpload", bulkUploadData);
//SqlParameter returnParameter = cmd.Parameters.Add("#result", SqlDbType.NVarChar);
//returnParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#result", SqlDbType.NVarChar,3000);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
query = (string)(cmd.Parameters["#result"].Value.ToString());
con.Close();

Attempting to connect to Excel spreadsheet in C#

I am trying to pull a bunch of data from a spreadsheet, however I am not able to make a successful connection in my C# code. B
Below is the connection string and the code that I am using to make the connection. The goal of the program is to pull the data from the spreadsheet and deposit it into a SQL database. I cannot get past the connection.open() command, however without receiveing this error message:
"External table is not in the expected format"
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
string queryString = "SELECT * FROM [SQL AgentUnique ID Test Load$]";
try
{
OleDbDataReader reader;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
reader = command.ExecuteReader();
while (reader.Read())
{
counter++;
//Access db values
string compCode = "";
string agId = "";
string fName = "";
string lName = "";
string nameSuffix = "";
compCode = reader.GetValue(0).ToString();
agId = reader.GetString(1);
fName = reader.GetString(2);
lName = reader.GetString(3);
nameSuffix = reader.GetString(4);
sqlComm.Parameters.Add(companyCode);
sqlComm.Parameters.Add(agentID);
sqlComm.Parameters.Add(firstName);
sqlComm.Parameters.Add(lastName);
sqlComm.Parameters.Add(suffix);
//Initialize connection objects
cm = Dts.Connections["QUAHILSQ03"];
sqlConn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new SqlCommand("AgentResourcesU01.dbo.sp_AgentIdAprCheck", sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
//Execute stored procedure
sqlComm.ExecuteNonQuery();
}
reader.Close();
connection.Close();
OleDbConnection.ReleaseObjectPool();
}
For *.xlsx, you need the Ace drivers: Microsoft.ACE.OLEDB.12.0
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\nearod\Desktop\TestLoad.xlsx;
Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
Wrote this a long while back. It's in WebForms, but the .cs file shows you want you need:
converting an excel spreadsheet to a dataset, datatable and multi-dimensional array
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+FileToConvert+";Extended Properties=Excel 8.0;";
try
{
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
//this next line assumes that the file is in default Excel format with Sheet1 as the first sheet name, adjust accordingly
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connection);
DataSet ds = new DataSet();
DataTable dt = new DataTable();
adapter.Fill(ds);//now you have your dataset ds now filled with the data and ready for manipulation
// do stuff
}

Categories