|
You last visited: Today at 10:48
Advertisement
Excel to Datagridview to SQL (LINQ)
Discussion on Excel to Datagridview to SQL (LINQ) within the .NET Languages forum part of the Coders Den category.
02/02/2016, 17:22
|
#1
|
elite*gold: 0
Join Date: Apr 2012
Posts: 372
Received Thanks: 21
|
Excel to Datagridview to SQL (LINQ)
WEll i have an excel file that i want to read and display in datagridview and i managed to finish that, now im asking for some help with the part to export the data to a SQL database...
can someone show me an easy example how to export that data to sql?
this is how i got it from excel to datagridview:
Code:
public void importExcel(string path, string sheetName) {
var excel = new LinqToExcel.ExcelQueryFactory(path);
excel.ReadOnly = true;
var companies = from a in excel.Worksheet(sheetName) select a;
var columnNames = excel.GetColumnNames(sheetName);
DataTable dtExcelRecords = new DataTable();
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in companies)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
dataGWlist.DataSource = dtExcelRecords;
}
i know i ahve to make the sql connection etc,
but the question is can i read throught the excel file directly and upload data or do i have to save it to an array or something and then manually insert each row/cell ?
right now i have something like this:
Code:
DataContext db = new DataContext(@""+connection);
Monitoring monitor = new Monitoring();
string[] arrayAddr = new string[dataGWseznam.Rows.Count];
for (int i = 0; i < stCol; i++)
{
arrayAddr[i] = Convert.ToString(dataGWseznam.Columns[i].HeaderText);
}
int colcount=dataGWseznam.Columns.Count;
int rowcount=dataGWseznam.Columns.Count;
string[,] array2D = new string[rowcount, colcount];
for (int x = 0; x < colcount; x++)
{
for (int i = 0; i < rowcount; i++)
{
array2D[x, i] = Convert.ToString(dataGWseznam.Rows[x].Cells[i].Value);
db.ExecuteCommand("INSERT into Monitoring ("+arrayAddr[x]+") VALUES ('" + array2D[x, i] + "');");
//string msg = string.Format("{0} ", array2D[x, i]);
//MessageBox.Show(msg);
}
}
//Save changes to Database.
db.SubmitChanges();
lblStatusSql.Text = "Finished";
|
|
|
02/04/2016, 10:05
|
#2
|
elite*gold: 0
Join Date: Apr 2012
Posts: 372
Received Thanks: 21
|
i decided i will use datagridview and send that to sql after i've ported the data from excel to the datagridview
Code:
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGWseznam.Rows)
{
string constring = @"I have a source in my project but modded for forum post";
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 VALUES(@DATE, @TIME, @TITLE)", conn))
{
cmd.Parameters.AddWithValue("@DATE", row.Cells["date"].Value);
cmd.Parameters.AddWithValue("@TIME", row.Cells["time"].Value);
cmd.Parameters.AddWithValue("@TITLE", row.Cells["title"].Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
MessageBox.Show("Records inserted.");
}
but i get a exception at conn.Open();
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
|
|
|
02/04/2016, 10:54
|
#3
|
dotCom
elite*gold: 9842
Join Date: Mar 2009
Posts: 16,866
Received Thanks: 4,684
|
Quote:
Originally Posted by Hikarim
i decided i will use datagridview and send that to sql after i've ported the data from excel to the datagridview
Code:
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGWseznam.Rows)
{
string constring = @"I have a source in my project but modded for forum post";
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 VALUES(@DATE, @TIME, @TITLE)", conn))
{
cmd.Parameters.AddWithValue("@DATE", row.Cells["date"].Value);
cmd.Parameters.AddWithValue("@TIME", row.Cells["time"].Value);
cmd.Parameters.AddWithValue("@TITLE", row.Cells["title"].Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
MessageBox.Show("Records inserted.");
}
but i get a exception at conn.Open();
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
|
Try this
Code:
private void btnTest_Click_1(object sender, EventArgs e) {
foreach (DataGridViewRow row in dataGWseznam.Rows) {
string constring = @"yeah yeah your connect line";
using (SqlConnection conn = new SqlConnection(constring))
using (SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 VALUES(@DATE, @TIME, @TITLE)", conn)) {
cmd.Parameters.AddWithValue("@DATE", row.Cells["date"].Value);
cmd.Parameters.AddWithValue("@TIME", row.Cells["time"].Value);
cmd.Parameters.AddWithValue("@TITLE", row.Cells["title"].Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
MessageBox.Show("Records inserted.");
}
when this not work, check if in row.Cells are the right values
|
|
|
02/04/2016, 11:42
|
#4
|
elite*gold: 0
Join Date: Apr 2012
Posts: 372
Received Thanks: 21
|
Quote:
Originally Posted by Devsome
Try this
Code:
private void btnTest_Click_1(object sender, EventArgs e) {
foreach (DataGridViewRow row in dataGWseznam.Rows) {
string constring = @"yeah yeah your connect line";
using (SqlConnection conn = new SqlConnection(constring))
using (SqlCommand cmd = new SqlCommand("INSERT INTO Table_1 VALUES(@DATE, @TIME, @TITLE)", conn)) {
cmd.Parameters.AddWithValue("@DATE", row.Cells["date"].Value);
cmd.Parameters.AddWithValue("@TIME", row.Cells["time"].Value);
cmd.Parameters.AddWithValue("@TITLE", row.Cells["title"].Value);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
MessageBox.Show("Records inserted.");
}
when this not work, check if in row.Cells are the right values
|
Okay, i found the problem, i had a double slash in my connection string,.. so now thats working, but i get a primary key violation (that it cant be null) how can i fix that? Because if i add something like this:
cmd.Parameters.AddWithValue("@id", 1012);
i get te key duplication error...
|
|
|
02/04/2016, 11:57
|
#5
|
dotCom
elite*gold: 9842
Join Date: Mar 2009
Posts: 16,866
Received Thanks: 4,684
|
Then use the auto_increment function, so you don't need to fill the ID.
Quote:
|
The PRIMARY KEY constraint uniquely identifies each record in a database table.
|
|
|
|
02/04/2016, 12:15
|
#6
|
elite*gold: 0
Join Date: Apr 2012
Posts: 372
Received Thanks: 21
|
Aaam, sorry for being a noob, but how should i do this? -can u give me a code example please?
|
|
|
02/04/2016, 13:09
|
#7
|
dotCom
elite*gold: 9842
Join Date: Mar 2009
Posts: 16,866
Received Thanks: 4,684
|
We need to take a look at your Table design.
It should look like
When your ID is auto_increment, you don't need:
Code:
cmd.Parameters.AddWithValue("@id", 1012);
or you are using a update query and the ID is for the where clause
|
|
|
02/04/2016, 13:17
|
#8
|
elite*gold: 0
Join Date: Apr 2012
Posts: 372
Received Thanks: 21
|
The table in the database is like this:
ID int PRIMARYKEY
DATE varchar(50) notnull
TIME varchar(50) notnull
TITLE varchar(50) notnull
as for the dataTable, i get it like this:
Code:
DataTable dtExcelRecords = new DataTable();
public void importExcel(string path, string sheetName)
{
var excel = new LinqToExcel.ExcelQueryFactory(path);
excel.ReadOnly = true;
var companies = from a in excel.Worksheet(sheetName) select a;
var columnNames = excel.GetColumnNames(sheetName);
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in companies)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
dataGWseznam.DataSource = dtExcelRecords;
}
|
|
|
 |
Similar Threads
|
C# DataGridView Add Form
05/01/2015 - .NET Languages - 2 Replies
Hey Leute,
Ich bin noch ein Anfänger in C# und bin dabei es zu lernen.
Ich habe mir ein kleines Projekt vorgenommen. Auf der Form1 ist ein DataGridView mit folgenden Columns:
BookNr, BookName, BookAutor
So, mit einen Button wird eine zweite Form geöffnet, mit dieser zweiten Form möchte ich Daten in das DataGridView hinzufügen. 3 TextBox und einen Button "Hinzufügen".
|
C# DataGridView
05/24/2013 - .NET Languages - 10 Replies
Hallo Com
Ich möchte gerne alle Daten aus meiner DataGridView in eine CSV-Datei speichern
Wie ist dies möglich?
MFG
|
DataGridView Profie ;)
09/27/2012 - .NET Languages - 3 Replies
Guten Tag,
ich würde mich freuen, wenn ein erfahrender DataGridView (vb.net) sich bei mir melden könnte. Habe nur ein kleines Problem.
Biete ein Großes danke und ein Thanks. ( Dauer ca. 2-5 min )
MFG Marcell110
( Rechtschreibung etc. nicht beachten :D jeder weiß was gemeint ist und ich habe keine lust jetzt meine SHIFT taste zudrücken )
|
Datagridview hilfe
09/19/2012 - .NET Languages - 0 Replies
Hey, bekomm das mit dem DGV ned hin, dass wenn ich was eintrage - dies auch abgespeichert wird :@
Imports System.Data.OleDb
Public Class Artikeldatenbank
Dim cmd As OleDbCommand
Dim conn As OleDbConnection
Dim adapter As OleDbDataAdapter
Dim builder As OleDbCommandBuilder
|
Zeilenumbruch im DataGridView?
08/27/2012 - .NET Languages - 1 Replies
Hey kannst Ihr mir sagen wie ich einem Qullcode in eine spalte laden?
Also der Quellcode sieht so au
<b>Login Erfolgreich</b><br>NoLagg v1.58.8<br>Essentials v2.7.2<br>WorldEdit v5.1.1<br>WorldGuard v5.3<br>
wie bekomme ich es hin, dass er pro spalte ein addon ist also so
|
All times are GMT +1. The time now is 10:49.
|
|