to import certain cells in the column in Excel to C # - c#

My excel file is that column1A: city,ankara,ankara,ankara,istanbul,istanbul,izmir
I want to that combobox looks like ankara,istanbul,izmir
it doesn't again.
OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");
baglan.Open();
string sql = "Select * From [Sayfa1$A1:A100] ";
OleDbCommand komut = new OleDbCommand(sql, baglan);
OleDbDataReader dr = null;
dr = komut.ExecuteReader();
while (dr.Read())
{
if (dr[0] != "")
{
combobox1.Items.Add(dr[0].ToString());
}
else
{
break;
}
}
baglan.Close();

if (dr[0] != ""){
if(!combobox1.Items.Contains(dr[0])){
combobox1.Items.Add(dr[0].ToString());
}
}

Try this:
OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");
baglan.Open();
string sql = "Select * From [Sayfa1$A1:A100] ";
OleDbCommand komut = new OleDbCommand(sql, baglan);
OleDbDataReader dr = null;
dr = komut.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
// To Copy distinct values from specified column to a different datatable
DataTable diffValues = dt.DefaultView.ToTable(true, "ColName");
combobox1.DataSource = datatable;
It works for me.

Related

getoledbschematable requires an open and available connection.The connection's current state is closed

My code below gives me the following error as i typed in the title
What am I doing wrong here?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
conn = new OleDbConnection(pathConn);
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
spreadSheetData starts falling null
my codes refer to Excel to DataGridView
1st answered by JohnG
and this video https://www.youtube.com/watch?v=CfNMPDJVjPI
Thanks for any help!
Your code should be something like this:
I have encapsulated your connection inside a using, so we are sure freeing resources. Also it's necessary to open the connection.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Prepare things
using(OleDbConnection conn = new OleDbConnection(pathConn))
{
conn.Open(); //Added this line
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
//Do staff
}
}
}
You must open your connection before using it :
conn = new OleDbConnection(pathConn);
conn.Open();
You should also use the "Using" statement to properly dispose the connection when not used anymore.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
//OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
using(OleDbConnection conn = ew OleDbConnection(pathConn))
{
//conn = new OleDbConnection(pathConn);
conn.Open();
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
}

How to import data to GridView Using Linq To Excel

I want to import data to gridview from Excel. And I have done using System.Data.OleDb as
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
How to achieve the same using LinqToExcel
Try this
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
ExcelQueryFactory excelFile = new ExcelQueryFactory(fileLocation);
var data = from a in excelFile.Worksheet("Sheet1") select a;
var columnNames = excelFile.GetColumnNames("Sheet1");
DataTable dtExcelRecords = new DataTable();
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in data)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
gv.DataSource = dtExcelRecords;
gv.DataBind();
}

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();
}
}

Uploading a file into SQL Server

Reword the question... the below code inserts the data into an SQL Server database, and into the correct table however, the data is not inserted correctly... here is the code
if (FileUpload1.HasFile)
{
string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
OleDbConnection OleDbcon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";");
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", OleDbcon);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(cmd);
OleDbcon.Open();
DbDataReader dr = cmd.ExecuteReader();
string con_str = #"Data Source=ENERGYSQL\ENERGY;Initial Catalog=ProjectHandler;Persist Security Info=True;User ID=aconyon;Password=birchall";
SqlBulkCopy bulkInsert = new SqlBulkCopy(con_str);
bulkInsert.DestinationTableName = "StockTable";
bulkInsert.WriteToServer(dr);
OleDbcon.Close();
Array.ForEach(Directory.GetFiles((Server.MapPath("~/temp/"))), File.Delete);
//Label1.ForeColor = Color.Green;
Label1.Text = "Successfully inserted";
}
else
{
//Label1.ForeColor = ConsoleColor.Red;
Label1.Text = "please select ther File";
}
what this code does is select the far most right column, in my example Quantity, and insert just this into the database, ignoring all other rows (A and B) do i need to change the OleDbCommand to select certain rows. A(ItemName), B(Date), C(Quantity)
use this code.
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source={0};Extended Properties='Excel 8.0;HRD=YES;IMEX=1'",
Server.MapPath(#"~\DownloadedExcelFilesOp4\myfile" + fileExt));// + "\\" +
FileUploadControl.PostedFile.FileName.ToString());
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand(("Select [Demo1] ,[Demo2] FROM [Sheet1$]"),
connection);
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
}
}
You can use query like below to get the value of any particular column.
OleDbCommand command = new OleDbCommand(("Select [Col1] ,[Col2] FROM [Sheet1$]"),
connection);

insert data in sqlite using dataset in c#

I have one excel sheet from which I am getting data in dataset using OleDbConnection
private static DataSet ImportExcel(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +
";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
}
return output;
}
Now I want to Insert data from this dataset to sqlite table.
This is how we can do it
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}

Categories

Resources