The following code return empty cells for the ones who are stored as text" Number Stored as Text" How can I get the value of these cells ?
string connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HDR=yes;IMEX=2';");
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con1 = new OleDbConnection(connectionString))
{
var dt = new DataTable();
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con1.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con1);
adapter.Fill(dt);
for (int i = 1; i < dt.Rows.Count; i++)
{
for (int j = 1; j < dt.Columns.Count; j ++)
{
MessageBox.Show(dt.Rows[0][j].GetType().ToString());
}
}
var cell = dt.Rows[0][j] == System.DBNull.Value ? "null...", dt.Rows[0][j];
Use IMEX=1 for mixed types in connection string.
Related
I tried to get 4 names from first table and check how frequent 4 of the names appeared in each of another 20 groups and then update it on groupevenfrequency. However, I have encountered error on this coding. Appreciate if someone can assist. Thanks.
From this coding, why str[1] and str[2] and str[3] and str[4] is same teachername? But the sql command SELECT DISTINCT is already resulted 4 different teachers. Please advice.
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd = new SQLiteCommand();
cmd = dbConnect.CreateCommand();
cmd.CommandText = "SELECT DISTINCT Teacher_Name from " + myTeacher + " Order by Sum_Weekly_Credit desc LIMIT 4";
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
da.Fill(dt);
string[] str = new string[5];
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
dbConnect.Close();
dbConnect = new SQLiteConnection("Data Source=school.db;Version=3;");
dbConnect.Open();
cmd2 = new SQLiteCommand();
cmd2 = dbConnect.CreateCommand();
cmd3 = new SQLiteCommand();
cmd3 = dbConnect.CreateCommand();
for (int j = 1; j <= 20; j++)
{
cmd2.CommandText = "SELECT Subject FROM Group_Even_" + j + " WHERE Teacher_Name = #Teacher_Name1 OR Teacher_Name = #Teacher_Name2 OR Teacher_Name = #Teacher_Name3 OR Teacher_Name = #Teacher_Name4";
cmd2.Parameters.AddWithValue("#Teacher_Name1", str[1]);
cmd2.Parameters.AddWithValue("#Teacher_Name2", str[2]);
cmd2.Parameters.AddWithValue("#Teacher_Name3", str[3]);
cmd2.Parameters.AddWithValue("#Teacher_Name4", str[4]);
DataTable dt2 = new DataTable();
SQLiteDataAdapter da2 = new SQLiteDataAdapter(cmd2);
da2.Fill(dt2);
if (dt2.Rows.Count > 0)
{
int TempCountFrequency = dt2.Rows.Count;
cmd2.CommandText = "UPDATE GroupEvenFrequency SET GroupEven_Frequency = #GroupEven_Frequency WHERE GroupEven_Name = Group_Even_" + j + "";
cmd2.Parameters.AddWithValue("#GroupEven_Frequency", TempCountFrequency);
cmd2.ExecuteNonQuery();
}
else
{
continue;
}
}
The code you have here looks wrong....
for (int i = 1; i <= 4; i++)
{
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
cmd.ExecuteNonQuery();
}
}
Surely you are expecting the dt.Rows to contain the 4 names you are interested in? So why have the outer loop.
So shouldn't it be more like...
string[] str = new string[5];
int i = 1;
foreach (DataRow dr in dt.Rows)
{
str[i] = dr["Teacher_Name"].ToString();
i++;
}
But as others have pointed out your overall approach could do with a rethink. The code won't cater for the fact that you might not have 4 distinct teacher names
I'm trying to append Excel table data into DataGridView (dgvInitial). At the beginning I'm initializing DGV by
private void DataForm_Load(object sender, EventArgs e)
{
int column = 100;
int rows = 1000;
dgvInitial.AutoGenerateColumns = false;
for (int i = 1; i <= column; i++)
{
dgvInitial.Columns.Add("Col_" + i, "Col_" + i);
dgvInitial.Columns[i - 1].FillWeight = 1;
}
for (int j = 0; j < rows; j++)
dgvInitial.Rows.Add();
foreach (DataGridViewColumn col in dgvInitial.Columns)
{
col.SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
and in loadToolStripMenuItem_Click event I'm trying to append excel table into dgv (source code used from another stackoverflow task but the question is very different)
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(#"provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Sample.xlsx';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dgvInitial.DataSource = DtSet.Tables[0];
MyConnection.Close();
but it's only reducing count of rows in dgv and I cannot see any data. When I comment everything in DataForm_Load event so it is working fine.
Please, do you have any idea, how can solve this issue? Thank you very much in advance.
Try this format for Connection String,
string Connectionstr = "";
string filePath ="C:\Sample.xlsx";
string fileExtension = Path.GetExtension(filePath).ToLower();
if (fileExtension == ".xls")
Connectionstr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
if (fileExtension == ".xlsx")
Connectionstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'";
MyConnection = new System.Data.OleDb.OleDbConnection(Connectionstr);
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dgvInitial.Columns.Clear();
dgvInitial.AutoGenerateColumns = true;
dgvInitial.DataSource = DtSet.Tables[0];
MyConnection.Close();
I am importing an Excel sheet into a SQL Server database. The Excel sheet contains 3 columns
id|data|passport
I am using SqlBulkCopy
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
string[] filePaths = null;
string strFileType = null;
string strFileName = null;
string strNewPath = null;
int fileSize;
int flag=0;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
fileSize = FileUpload1.PostedFile.ContentLength / 1024;
//EXCEL DETAILS TABLE
con.Open();
//=========================================
DataTable dt8 = new DataTable();
SqlCommand cmd8 = new SqlCommand("insert into exceldetails (name,type,details,size)" + "values(#name,#type,#details,#size)", con);
cmd8.Parameters.Add("#name", SqlDbType.VarChar).Value = strFileName;
cmd8.Parameters.Add("#type", SqlDbType.VarChar).Value = strFileType;
cmd8.Parameters.Add("#details", SqlDbType.VarChar).Value = DateTime.Now;
cmd8.Parameters.Add("#size", SqlDbType.Int).Value = fileSize;
cmd8.ExecuteNonQuery();
con.Close();
try
{
SqlDataAdapter da8 = new SqlDataAdapter(cmd8);
da8.Fill(dt8);
}
catch { }
//=========================================
//CHOOSING EXCEL CONNECTIONSTRING
string excelConnectionString = "";
switch (strFileType)
{
case ".xls":
excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
break;
case ".xlsx":
{
excelConnectionString = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 12.0 Xml;");
break;
}
}
//===================================
//PRE EXCEL COUNT
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
OleDbCommand command = new OleDbCommand("Select ID,Data,passport FROM [Sheet1$]", connection);
OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]", connection);
//Sql Server Table DataTable
DataTable dt4 = new DataTable();
SqlCommand cmd4 = new SqlCommand("select * from excelsheet", con);
try
{
SqlDataAdapter da4 = new SqlDataAdapter(cmd4);
da4.Fill(dt4);//sql table datatable
}
catch { }
//===============================
//excelsheet datatable
DataTable oltlb = new DataTable();
OleDbCommand olcmd = new OleDbCommand("select * from [Sheet1$]", connection);
try
{
OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
olda.Fill(oltlb); //excel table datatable
}
catch { }
//==============================
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=DITSEC3;Initial Catalog=test;Integrated Security=True";
con.Open();
DataTable dt7 = new DataTable();
dt7.Load(dr);
DataRow[] ExcelRows = new DataRow[dt7.Rows.Count];
DataColumn[] ExcelColumn = new DataColumn[dt7.Columns.Count];
//=================================================
for (int i1 = 0; i1 < ExcelRows.Length; i1++)
{
string a = ExcelRows[i1]["passport"].ToString();
char a1 = a[0];
if (a1 >= 'A' || a1 <= 'Z')
{
Label12.Text = "CAPITAL";
break;
}
else
{
Label12.Text = "notgood";
flag = flag + 1;
}
}
//=========================================================
if (flag == 0)
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
dt7.Rows.CopyTo(ExcelRows, 0);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["passport"] == DBNull.Value)
{
ExcelRows[i]["passport"] = 0;
}
}
bulkCopy.WriteToServer(ExcelRows);
//==========================================================================================
for (int i = 0; i < ExcelRows.Length; i++)
{
if (ExcelRows[i]["data"] == DBNull.Value)
{
// Include any actions to perform if there is no date
//ExcelRows[i]["data"] = Convert.ToDateTime("0");
}
else
{
DateTime oldDate = Convert.ToDateTime(ExcelRows[i]["data"]).Date;
DateTime newDate = Convert.ToDateTime(oldDate).Date;
ExcelRows[i]["data"] = newDate.ToString("yyyy/MM/dd");
}
}
//==========================================================================================
}
//======
}
else
{
Label13.Text = "Wrong Format";
}
}
}
}
}
ERROR AT :
string a = ExcelRows[i1]["passport"].ToString();
ERROR:
Object reference not set to an instance of an object.
I have an excel sheet similar to :
I want to read data columns header:All,col1,col2,col3,col4,col5
and get all cell data.for example cell in Row = 2 and column 2 = 0
I currently write this code :
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT top 5 * FROM " + excelSheets[j], connString);
DataTable fooData = new DataTable();
dbAdapter.Fill(fooData);
foreach (DataRow row in fooData.Rows)
{
Response.Write(row[0].ToString());
//Response.Write(row[1].ToString());
}
but it return just a data table with 1 column and just row 1..5 text.
How I can do this?
Please say answer without using Linq to Excel Provider and Open Xml.
Edit 1:
string file_name = "C:\\Book1.xlsx";
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + file_name + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
Response.Write("Not Exist");
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
// Loop through all of the sheets if you want too...
for (int j = 0; j < excelSheets.Length; j++)
{
OleDbDataAdapter dbAdapter = new OleDbDataAdapter("SELECT top 100 * FROM " + excelSheets[j], connString);
DataTable fooData = new DataTable();
dbAdapter.Fill(fooData);
foreach (DataRow row in fooData.Rows)
{
Response.Write(row[0].ToString());
}
}
You get the column name for the first column for example by fooData.Columns[0].ColumnName - see http://msdn.microsoft.com/en-us/library/system.data.datacolumn.columnname.aspx
EDIT:
Change the SELECT to SELECT * FROM AND use Fill (0, 5, new DataTable[] { fooData }).
"SELECT * FROM [" + excelSheets[j] + "$A1:C5]"
Try this one. It should return all of the cells from A1 to C5.
The driver that you selected is for Excel 2007 ("Provider=Microsoft.ACE.OLEDB.12.0" in your connectionString). Is your Excel file 2007 or 2010?
For Only data column header for logic is here:
string filePath = "C:\\Book1.xlsx";
string connString = string.Empty;
if (path.EndsWith(".xlsx"))
{
//2007 Format
connString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", path);
}
else
{
//2003 Format
connString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=No'", path);
}
using (OleDbConnection con = new OleDbConnection(connString))
{
using (OleDbCommand cmd = new OleDbCommand())
{
//Read the First Sheet
cmd.Connection = con;
con.Open();
DataTable dtExcelSchema = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
con.Close();
string firstSheet = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
//Read the Header Row
cmd.CommandText = "SELECT top 1 * From [" + firstSheet + "]";
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
DataTable HeaderColumns = new DataTable();
da.SelectCommand = cmd;
da.Fill(HeaderColumns);
List<string> Filedata = new List<string>();
foreach (DataColumn column in HeaderColumns.Columns)
{
string columnName = HeaderColumns.Rows[0][column.ColumnName].ToString();
Filedata.Add(columnName);
ViewBag.Data = Filedata;
}
}
}
}
code :
SqlConnection sqlc = new SqlConnection(
"Data Source=" + Environment.MachineName + #"\SQLEXPRESS;" +
"Integrated security=true;" +
"database=someDB");
SqlCommand sqlcmd;
string tmp = string.Empty;
for(int i = 0; i < 100000; i++)
{
tmp += "inserto into [db].[Files](...) values (...);"
}
sqlcmd = new SqlCommand(tmp, sqlc);
try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } cathc{}
inserted only < 1000 writes
How write all 100000 writes ?? May be destroy and create sqlcmd?
You should probably split the commands up into smaller commands. Say, inserting 500 records per SqlCommand until you've inserted all your records.
int totalRecordsToWrite = 100000;
int maxRecordsPerCommand = 500;
SqlConnection sqlc = new SqlConnection(
"Data Source=" + Environment.MachineName + #"\SQLEXPRESS;" +
"Integrated security=true;" +
"database=someDB");
int currentRecord = 0;
while (currentRecord < totalRecordsToWrite)
{
SqlCommand sqlcmd;
string tmp = string.Empty;
for(int j = 0; j < maxRecordsPerCommand; j++)
{
currentRecord++;
if (currentRecord >= totalRecordsToWrite)
break;
// Insert record "currentRecord" of the 100000 here.
tmp += "inserto into [db].[Files](...) values (...);"
}
using (sqlcmd = new SqlCommand(tmp, sqlc))
{
try { sqlc.Open(); sqlcmd.ExecuteNonQuety(); } catch{}
}
}