How do I delete the empty rows in my dataset?
I am reading data from an excel spreadsheet that has a few empty rows at the bottom.
Here is my code so far:
ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", VariableFile);
OleDbConnection objConn = new OleDbConnection(ConnectionString);
objConn.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Requirements$]", objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataSet objDataset1 = new DataSet();
objAdapter1.Fill(objDataset1);
objConn.Close();
Why not just modify your query to pull only the non-empty data.
Every solution I have found told me to modify the Excel query like you have it. So that isn't much help. You could just create a DataView from your Table that would look at the non-blank rows. Do you know what the columns are beforehand? Even if you don't you could still loop over the column names and build a filter string for the DataView.
string filter = "";
foreach (DataColumn dc in dt.Columns)
{
filter += dc.ColumnName + " <> '' ";
if (dt.Columns[dt.Columns.Count-1].ColumnName != dc.ColumnName)
{
filter += " AND ";
}
}
DataView view = new DataView(dt);
view.RowFilter = filter;
dt = view.ToTable();
Use Linq to include only rows that have a non-null/blank value in any of its columns.
var filteredData = sourceDataTable.AsEnumerable()
.Where(row => row.ItemArray.Any(col => !String.IsNullOrWhiteSpace(col.ToString())))
.ToArray();
Related
I have 2 different databases - SQLite and PostgreSQL and i trying to make tiny math on table from this databases.
Both tables contains columns nr_serii and ilosc, SQLite:
And Postgres:
I established a connection to both databases and populate dataset. Maybe i should use different place to store the data?
I need to substraction column ilosc: (sqlite-postgres), but not know how to do that.
For example, for each nr_serii make substraction column ilosc:
nr_serii:222222
ilosc:15-7=8
Finally i want to show output data to datagridview.
When i use messagebox i can see the data in dataset. Here is my part of code:
string cs = #"URI = file:" + Sdatabase;
string csP = conParam;
string sqlP = "select nr_serii, ilosc from stany";
string sql = "select nr_serii, ilosc from przychod";
using var con = new SQLiteConnection(cs);
con.Open();
using var cmd = new SQLiteCommand(sql, con);
SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
using var conP = new NpgsqlConnection(csP);
conP.Open();
NpgsqlCommand cmdP = new NpgsqlCommand(sqlP, conP);
NpgsqlDataAdapter DA = new NpgsqlDataAdapter(cmdP);
DataSet dsP = new DataSet();
DA.Fill(dsP);
//----------test-----------
foreach (DataRow row in dsP.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
MessageBox.Show(nr_serii +","+ ilosc);
}
//--------------------------
For example, you can browse data table from first datasource ds and search for a matching row by value of nr_serii column for each row in the datatable in second datasource dsP, and if found, add a new row with the calculation result to the new third result table.
Then you don't forget to solve the problem of what to do with records that are only in the first ds or only in the second dsP datasource, depending on the value of the nr_serii column.
Program code example:
//prepare result third DataTable
DataTable resultDt = new DataTable();
resultDt.Columns.Add("nr_serii");
resultDt.Columns.Add("ilosc");
//add content to result DataTable
foreach (DataRow row in ds.Tables[0].Rows)
{
var nr_serii = row["nr_serii"];
var ilosc = row["ilosc"];
DataRow drP = null;
foreach (DataRow dataRow in dsP.Tables[0].Rows)
{
if (nr_serii.ToString() == (string)dataRow["nr_serii"])
{
drP = dataRow;
break;
}
}
if (drP != null)
{
var dr = resultDt.NewRow();
dr["nr_serii"] = nr_serii;
dr["ilosc"] = (int)ilosc - (int)drP["ilosc"];
resultDt.Rows.Add(dr);
}
}
I have a datagridview and I filled with data.
DataTable table = new DataTable();
dataGridView1.DataSource = table;
con = new SqlDataAdapter("SELECT * FROM TABLE "'", con);
ds = new System.Data.DataSet();
con .Fill(ds, "TABLE");
My problem is I have to add rows manually like the code below but it is just add one row.But what I need foreach's count row.
foreach (var a in names.Split(new char[] { ';' }))
{
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i + 1].Cells[3].Value = a.ToString();
i = i +1;
}
Try to use
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);
I need to read a single cell from an xsl excel file to a string withing the web application i am building. I was previously pulling cell ranges from the file to a table using the following code:
string PullFromExcell(string CellNo)
{
string cell;
string properties = String.Format(#"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = C:\Users\User\Desktop\file.xls; Extended Properties = 'Excel 8.0;'");
using (OleDbConnection conn = new OleDbConnection(properties))
{
string worksheet = "Sheet";
conn.Open();
DataSet ds = new DataSet();
using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + worksheet + "$" + CellNo + "]", properties))
{
DataTable dt = new DataTable();
cell = dt.ToString();
da.Fill(dt);
ds.Tables.Add(dt);
grdComponent.DataSource = dt;
grdComponent.DataBind();
}
}
return cell;
}
How would i send that to a string? The code that i would use when pulling from a database is similar to this:
Sqlstring = "Select data from variable where name = 'fred' and ssn = 1234";
var cmd0 = new SqlCommand(Sqlstring, Class_Connection.cnn);
string Data = cmd0.ExecuteScalar().ToString();
i'm just not sure if any of that is compatible.
After filling DataTable, you can search the row like this:
foreach (DataRow dr in dt.Rows)
{
if (dr["name"] == "fred" && dr["ssn"] == "1234")
{
cell = dr["data"].ToString();
break;
}
}
Hi I am importing a excel or a .csv file using OpenFileDialog in Visual Studio 2005.
I need to show all the headers in a list, which is supposed to be listed on a ComboBox.
e.g If I import a file which has 10 columns in it, my drop down should show me 10 values as
1, 2, 3..........10
Please let me know how to go about it.
CSV is completely different animal than Excel.
I would use the OpenXml library OR use the OleDb driver to read from the excel file.
Look here: Reading excel file using OLEDB Data Provider
You will need to have the ACE driver installed, you may already have it though.
// first read *.xls file into a DataTable; don't wory it is very quick.
public DataTable ReadExcelFile(string strFilePath)
{
string sConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + "; Extended Properties=\"Excel 8.0; HDR=No; IMEX=1;\"";
OleDbConnection objConn = new OleDbConnection(sConnectionString);
objConn.Open();
DataTable sdt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
// Change this part to read 1 row
String str = "SELECT TOP(2) * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
//String str = "SELECT * FROM [" + sdt.Rows[0]["TABLE_NAME"].ToString() + "]";
OleDbCommand objCmdSelect = new OleDbCommand(str, objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
DataTable dt = new DataTable();
objAdapter1.Fill(dt);
objConn.Close();
dt.AcceptChanges();
return dt;
}
Now working with DataTable
DataTable dt = ReadExcelFile(#"c:\\x.xlsx");
if (dt != null)
{
System.Windows.Forms.ComboBox cmb = new System.Windows.Forms.ComboBox();
for (int i = 0; i < dt.Columns.Count; i++)
cmb.Items.Insert(i, dt.Columns[i].ColumnName);
}
I'm importing excel into DataTable. The excel file contains 50x7 cells with data.
The problem is that the Fill() method imports 368(?) rows regardless the fact that the data is in the first 50 of them. Any idea what might be the problem ?
I'm using OleDbDataAdapter for the import.
connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
string commandString = "select * from [" + worksheetName + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(commandString, connectionString);
DataTable fileTable = new DataTable();
adapter.Fill(fileTable);
Try this to remove empty cells from the DataTable:
adapter.Fill(fileTable);
fileTable = fileTable.AsEnumerable()
.Where(row => !row.ItemArray.All(f => f is System.DBNull || String.IsNullOrWhiteSpace(f.ToString())))
.CopyToDataTable();
Note that it also removes empty rows inside the sheet.