Adding data to data table without filling the column names C# - c#

I am trying to add data from an excel spreadsheet to a data table, I am getting the data no worries and adding it to the tables within the datasets but when I do add it, it fills the column names with the top row. I have tried to set the column names but then it just cuts off the top row of data.
I am fairly new to C#, I'm pretty sure I need to alter the fill method objAdapter1.Fill(objDataset1,tableName); but have no idea how to go about it.
public DataSet readExcel()
{
int x = 0;
string[] Individal_Runs = Directory.GetFiles(#"C:\testfiles");
DataSet objDataset1 = new DataSet();
int iso = 0;
foreach (string s in Individal_Runs)
{
x++;
try
{
String theConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Extended Properties=Excel 12.0 Xml";
OleDbConnection objConn = new OleDbConnection(theConnString);
objConn.Open();
string[] sheetnames = GetExcelSheetNames(String.Format("{0}", s));
int y = 0;
int z = 0;
string tableName;
bool looponce = false;
foreach (string sn in sheetnames)
{
OleDbCommand objCmdSelect = new OleDbCommand(String.Format("SELECT * FROM [{0}]", sn.ToString()), objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
if( looponce == false)
{
tableName = string.Format("isolations_{0}", iso);
objDataset1.Tables.Add(tableName);
objDataset1.Tables[tableName].NewRow();
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
looponce = true;
}
else
{
tableName = string.Format("isolations_{0}_{1}", iso,y);
objDataset1.Tables.Add(tableName);
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
y++;
}
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1,tableName);
int cols = objDataset1.Tables[tableName].Columns.Count;
for (int i = 0; i < cols; i++)
{
objDataset1.Tables[tableName].Columns[i].ColumnName = i.ToString();
}
z++;
}
iso++;
}

Related

How I can change rows places in datadridview?

Good afternoon, dear developers.
Faced such a problem:
there is DataGridVev, I have data lines in it. Depending on the toss-up, I need to sort the order of the rows in the display.
How can I do that?
As I understand the lines do not have an index, and the columns have.
Here is my code for sorting
for(int i = 0; i < 9; i++)
{
int tmp = i;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[2].Value == position[i])
{
Console.WriteLine(position[i] + "Место: " + tmp);
tmp += 9;
}
}
}
copied from the comment of the OP:
con = new SqlConnection();
con.ConnectionString = getConn;
con.Open();
adap = new SqlDataAdapter("SELECT * FROM " + table_name + " WHERE Groupe_year = #year ", con);
string year = comboBox1.Text;
adap.SelectCommand.Parameters.AddWithValue("#year", year);
ds = new System.Data.DataSet();
adap.Fill(ds, "Fighters_Details");
dataGridView1.DataSource = ds.Tables[0];
Assign the Data Source to a Data View instead.
dataGridView1.DataSource = ds.Tables[0].DefaultView;
For Sorting on the Groupe_year column as an example:
((System.Data.DataView)dataGridView1.DataSource).Sort = "Groupe_year";

Populating rows with data from a stored procedure using DataTables

I want to populate some fields on a PDF with data from a SQL database, I have a data access class that works but I can't get the values from the rows:
DataAccess DA = new DataAccess();
DataSet S = DA.CashData();
DataTable Cash = S.Tables[0];
DataTable Other = S.Tables[1];
DataTable Check = S.Tables[2];
DataTable Else = S.Tables[3];
string s = "";
foreach (DataRow row in Cash.Rows)
{
foreach (DataColumn col in Cash.Columns)
{
for (int i = 0; i < Cash.Columns.Count; i++)
{
DataRow cashRow = Cash.Rows[i];
s = s + cashRow[0].ToString() + ";";
}
}
Console.ReadLine();
}
string[] data = s.Split(';');
cell32.AddElement(new Paragraph(""));
cell32.AddElement(new Paragraph(data[0]));
cell32.AddElement(new Paragraph(data[1]));
The columns show data but the rows do not
If I understand your source correctly, you have a wrong execution in your loop for the rows, please consider this edited source:
DataAccess DA = new DataAccess();
DataSet S = DA.CashData();
DataTable Cash = S.Tables[0];
DataTable Other = S.Tables[1];
DataTable Check = S.Tables[2];
DataTable Else = S.Tables[3];
string s = "";
foreach (DataRow row in Cash.Rows)
{
for (int i = 0; i < row.Columns.Count; i++)
{
s += row[0].ToString() + ";";
}
Console.ReadLine();
}
string[] data = s.Split(';');
cell32.AddElement(new Paragraph(""));
cell32.AddElement(new Paragraph(data[0]));
cell32.AddElement(new Paragraph(data[1]));

C# All rows from MySQL query not going into datagridview

Im trying to fill a DataGridView with the results from a MySql Query however they are not all going in. Here is my code:
try
{
conn.Open();
player_search = new MySqlCommand("SELECT * FROM admin;", conn);
reader = player_search.ExecuteReader();
int counter = 0;
while (reader.Read())
{
player_list[0, counter].Value = reader.GetString(0);
player_list[1, counter].Value = reader.GetString(1);
player_list[2, counter].Value = reader.GetString(6);
player_list[3, counter].Value = reader.GetString(7);
player_list[4, counter].Value = reader.GetString(8);
player_list[5, counter].Value = reader.GetString(9);
player_list[6, counter].Value = "Remove";
counter = counter+1;
}
}
However it doesnt all go in. It only inserts the first row of the query? Why is it doing this? Im getting no errors?
Solved it! I had to do a long winded approach but it works!
MySqlCommand mysqlcmd = new MySqlCommand("SELECT * FROM admin;", conn);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
player_list.DataSource = dt;
int rowIndex = 0;
foreach (DataRow row in dt.Rows)
{
int i = 0;
foreach (var item in row.ItemArray)
{
if (i == 0) {
player_list[0, rowIndex].Value = item.ToString();
}
if (i == 1) {
player_list[1, rowIndex].Value = item.ToString();
}
if (i == 4)
{
player_list[2, rowIndex].Value = item.ToString();
}
if (i == 7)
{
player_list[3, rowIndex].Value = item.ToString();
}
if (i == 8)
{
player_list[4, rowIndex].Value = item.ToString();
}
if (i == 9)
{
player_list[5, rowIndex].Value = item.ToString();
}
player_list[6, rowIndex].Value = "Remove";
++i;
}
++rowIndex;
i = 0;
}
I would suggest you to try to get it using DataSet:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
UPDATE: player_list.DataSource(GetDBDataTable(...));
player_list.DataBind();

How to import all the Excel sheets to DataSet in C#

I've searched internet for this and couldn't really find a question like it. Everyone was looking for a way to import an individual sheet in the excel file but what I want is to import all the sheets in the file to DataTable's in DataSet without knowing the sheet names.
I've not done much things with Excel before. This a sample and partially working code I've found on the internet and it only parses the given sheet name:
public static DataSet Parse(string fileName, string workSheetName)
{
string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
string query = string.Format("SELECT * FROM [{0}$]", workSheetName);
DataSet data = new DataSet();
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(data);
}
return data;
}
In the code above, as you see, workSheetName should be passed in so the query can know where to look at to import. In my case, I want it to traverse all the sheets no matter what they are named like and import them to individual DataTable's of a DataSet.
So in essence, the final thing will be a DataSet in which each DataTable holds rows for each sheet in the imported file.
This is a code I came up with and it works perfect but I saw someone else already added an answer:
static DataSet Parse(string fileName)
{
string connectionString = string.Format("provider=Microsoft.Jet.OLEDB.4.0; data source={0};Extended Properties=Excel 8.0;", fileName);
DataSet data = new DataSet();
foreach(var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
var dataTable = new DataTable();
string query = string.Format("SELECT * FROM [{0}]", sheetName);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con= new OleDbConnection(connectionString);
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;
}
Because I was bored:
static void Main(string[] args)
{
string filename = #"c:\temp\myfile.xlsx";
System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " +
"data source='" + filename + "';" +
"Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ");
myConnection.Open();
DataTable mySheets = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
DataSet ds = new DataSet();
DataTable dt;
for (int i = 0; i <= mySheets.Rows.Count; i++)
{
dt = makeDataTableFromSheetName(filename, mySheets.Rows[i]["TABLE_NAME"].ToString());
ds.Tables.Add(dt);
}
}
private static DataTable makeDataTableFromSheetName(string filename, string sheetName)
{
System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " +
"data source='" + filename + "';" +
"Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ");
DataTable dtImport = new DataTable();
System.Data.OleDb.OleDbDataAdapter myImportCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + sheetName + "$]", myConnection);
myImportCommand.Fill(dtImport);
return dtImport;
}
The function that was suggested by Avitus is correct but it has logica error, you must rewrite in :
DataTable dtImport = new DataTable();
using ( System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0; " +
"data source='" + filename + "';" +
"Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ")){
using ( System.Data.OleDb.OleDbDataAdapter myImportCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [" + sheetName + "$]", myConnection))
myImportCommand.Fill(dtImport);
} return dtImport;
this is correct, otherwise you must dispose connection and dataadapter manually.
This might not be the best and the fastest one, but its another way (Edit- added elimination of blank cells):
public static DataSet ReadWorkbook(string excelFileName, bool useFirstRowAsColumnName = false)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
var workBook = excel.Workbooks.Open(excelFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);//MLHIDE
try
{
System.Data.DataSet ds = new DataSet(excelFileName);
foreach (var sheet0 in workBook.Worksheets)
{
var sheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet0;
try
{
var dt = readSheet(sheet, useFirstRowAsColumnName);
if (dt != null)
ds.Tables.Add(dt);
}
finally
{
releaseObject(sheet);
}
}
return ds;
}
finally
{
workBook.Close(true, null, null);
excel.Quit();
releaseObject(workBook);
releaseObject(excel);
}
}
/// <summary>
/// Returns null for empty sheets or if sheet is not found.
/// </summary>
public static DataTable ReadSheet(string excelFileName, string sheetName, bool useFirstRowAsColumnName = false)
{
var excel = new Microsoft.Office.Interop.Excel.Application();
var workBook = excel.Workbooks.Open(excelFileName, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);//MLHIDE
try
{
foreach (var sheet0 in workBook.Worksheets)
{
var sheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet0;
try
{
if (sheet.Name.Equals_Wildcard(sheetName))
{
var dt = readSheet(sheet, useFirstRowAsColumnName);
if (dt != null)
return dt;
}
}
finally
{
releaseObject(sheet);
}
}
return null;
}
finally
{
workBook.Close(true, null, null);
excel.Quit();
releaseObject(workBook);
releaseObject(excel);
}
}
/// <summary>
/// Returns null for empty sheets
/// </summary>
private static DataTable readSheet(Microsoft.Office.Interop.Excel.Worksheet sheet, bool useFirstRowAsColumnName = false)
{
using (Dece.Common.BeginChangeCurrentCultureBlock_EN_us())
{
var range = sheet.UsedRange;
try
{
object[,] values = (object[,])range.Value2;
int rowCount = values.GetLength(0);
int colCount = values.GetLength(1);
int rowCount0 = rowCount;
int colCount0 = colCount;
#region find row-col count
{
bool ok = false;
for (int row = rowCount; row > 0; row--)
if (!ok)
for (int col = colCount; col > 0; col--)
{
var val = values[row, col];
if ((val != null) && (!System.Convert.ToString(val).IsNullOrEmpty()))
{
rowCount = row;
ok = true;
break;
}
}
else
break;
}
{
bool ok = false;
for (int col = colCount; col > 0; col--)
if (!ok)
for (int row = rowCount; row > 0; row--)
{
var val = values[row, col];
if ((val != null) && (!System.Convert.ToString(val).IsNullOrEmpty()))
{
colCount = col;
ok = true;
break;
}
}
else
break;
}
#endregion
if ((rowCount > 0) && (colCount > 0))
{
var dt = new DataTable(sheet.Name);
dt.BeginLoadData();
try
{
for (int col = 1; col <= colCount; col++)
dt.Columns.Add_RenameIfRequired(useFirstRowAsColumnName ? values[1, col].ToString_NullProof() : col.ToString());
var arr = new object[colCount];
for (int row = useFirstRowAsColumnName ? 1 : 0; row < rowCount; row++)
{
for (int col = 1; col <= colCount; col++)
arr[col - 1] = values[row + 1, col];
dt.Rows.Add(arr);
}
}
finally
{
dt.EndLoadData();
}
return dt;
}
else
return null;
}
finally
{
releaseObject(range);
}
}
}
private static void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
throw new Exception("Unable to release the Object " + ex.ToString(), ex);//MLHIDE
}
finally
{
GC.Collect();
}
}
C#
A neat and tidy, minimal version that provides a dataset with tables named as per the sheets (without the trailing dollar):
private static OleDbConnection GetConnection(string filename, bool openIt)
{
// if your data has no header row, change HDR=NO
var c = new OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{filename}';Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\" ");
if (openIt)
c.Open();
return c;
}
private static DataSet GetExcelFileAsDataSet(OleDbConnection conn)
{
var sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new[] { default, default, default, "TABLE" });
var ds = new DataSet();
foreach (DataRow r in sheets.Rows)
ds.Tables.Add(GetExcelSheetAsDataTable(conn, r["TABLE_NAME"].ToString()));
return ds;
}
private static DataTable GetExcelSheetAsDataTable(OleDbConnection conn, string sheetName)
{
using (var da = new OleDbDataAdapter($"select * from [{sheetName}]", conn))
{
var dt = new DataTable() { TableName = sheetName.TrimEnd('$') };
da.Fill(dt);
return dt;
}
}
Use it like:
DataSet ds;
using(c = GetConnection(#"C:\path\to\your\xl.xlsx", true)
ds = GetExcelFileAsDataSet(c);
Or if you only want one table and you know all the exact sheet name you want (remember that they have a dollar on the end):
DataTable dt;
using(c = GetConnection(#"C:\path\to\your\xl.xlsx", true)
dt = GetExcelSheetAsDataTable(c, "Sheet1$");
VB.NET
Bonus! Note: needs a modern version of VB that understands things like string interpolation, With etc
Private Shared Function GetConnection(filename As String, openIt As Boolean) As OleDbConnection
'if your data has no header row, change HDR=NO
Dim c = New OleDbConnection($"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{filename}';Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"" ")
If openIt Then c.Open()
Return c
End Function
Private Shared Function GetExcelFileAsDataSet(conn As OleDbConnection) As DataSet
Dim sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, {Nothing, Nothing, Nothing, "TABLE"})
Dim ds = New DataSet()
For Each r As DataRow In sheets.Rows
ds.Tables.Add(GetExcelSheetAsDataTable(conn, r("TABLE_NAME").ToString()))
Next
Return ds
End Function
Private Shared Function GetExcelSheetAsDataTable(conn As OleDbConnection, sheetName As String) As DataTable
Using da = New OleDbDataAdapter($"select * from [{sheetName}]", conn)
Dim dt = New DataTable() With {.TableName = sheetName.TrimEnd("$"c)}
da.Fill(dt)
Return dt
End Using
End Function
Use it like:
Dim ds As DataSet
Using c = GetConnection("C:\path\to\your\xl.xlsx", True)
ds = GetExcelFileAsDataSet(c)
End Using 'closes connection
Or for a single sheet (Remember sheet names end in a dollar) whose name you know:
Dim dt As DataTable
Using c = GetConnection("C:\path\to\your\xl.xlsx", True)
dt = GetExcelSheetAsDataTable(c, "Sheet1$")
End Using 'closes connection

10 random rows from excel

Help me with my code, because i don't now how to do this simple task. How to select 10 random rows from excel file?
string filepath = #"C:\1.xlsx";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text""";
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
showdata.DataSource = ds.Tables[0];
If you create a DataGridView on your Windows Form called RandomExcelRows, create a button called button1 and put the following code inside the Click event handler for button1:
private void button1_Click(object sender, EventArgs e)
{
Excel.Range[] rows = RandomRows(10, #"C:\test\whatever.xlsx");
DataTable dt = new DataTable();
bool ColumnsCreated = false;
foreach(Excel.Range row in rows)
{
object[,] values = row.Value;
int columnCount = values.Length;
if(!ColumnsCreated)
{
for(int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(String.Format("Column {0}", i));
dt.Columns.Add(dc);
ColumnsCreated = true;
}
}
DataRow dr = dt.NewRow();
for (int i = 0; i < columnCount; i++)
{
dr[String.Format("Column {0}", i)] = values[1,i+1];
}
dt.Rows.Add(dr);
}
RandomExcelRows.DataSource = dt;
}
And then create a method underneath called RandomRows containing the following:
private Excel.Range[] RandomRows(int randomRowsToGet, string worksheetLocation, int worksheetNumber = 1, int lowestRow = 0, int highestRow = 99)
{
Excel.Range[] rows = new Excel.Range[randomRowsToGet];
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(worksheetLocation);
Excel.Worksheet worksheet = workbook.Worksheets[worksheetNumber];
List<int> rowNumbers = new List<int>();
bool allUniqueNumbers = false;
Random random = new Random();
while (!allUniqueNumbers)
{
int nextNumber = random.Next(lowestRow, highestRow);
if (!rowNumbers.Contains(nextNumber))
rowNumbers.Add(nextNumber);
if (rowNumbers.Count == randomRowsToGet)
allUniqueNumbers = true;
}
for (int i = 0; i < randomRowsToGet; i++)
{
rows[i] = worksheet.UsedRange.Rows[rowNumbers[i]];
}
Marshal.ReleaseComObject(excel);
return rows;
}
The program will take a random number of rows (this amount is specified by you) from the Spreadsheet you specify and place these rows into your DataGridView.
It's pretty crude, and needs refactoring but it is the basis of what you need. You could also get the string containing the file location from a textbox instead of hardcoding this, the same goes for the number of rows you want, and the other parameters such as minimum and maximum rows.
As well, you could use an OpenFileDialog to allow your user to browse to your excel file, etc etc.
Here is my solution:
string filepath = #"C:\1.xlsx";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text""";
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
// above code block is yours as is.
// below part is for sorting.
DataTable data = ds.Tables[0];
data.Columns.Add(new DataColumn("Guid"));
for (int i = 0; i < data.Rows.Count; i++)
{
data.Rows[i].SetField("Guid", Guid.NewGuid());
}
DataView dv = data.DefaultView;
dv.Sort = "Guid desc";
showdata.DataSource = dv.ToTable();

Categories