C# - Read from excel sheet and pass variables into function - c#

I'm basically looking for some ideas as to the best way of constructing code to read an excel file and create user accounts.
I already have the code to both read the excel file and create the accounts, however I'm unsure as to the best way of passing the data from the excel sheet into the "CreateUser" function.
Any help is appreciated.
Cheers.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
namespace INB201_SAMS.Admin
{
public partial class UploadList : System.Web.UI.Page
{
protected void UploadButton_Click(object sender, EventArgs e)
{
var upload = Path.Combine(Server.MapPath("~/upload"), "myfilename.xlsx");
CSVUpload.SaveAs(upload);
var excelConString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", upload);
using (OleDbConnection con = new OleDbConnection(excelConString))
{
con.Open();
OleDbCommand com = new OleDbCommand("Select * from [UserUpload$]", con);
OleDbDataReader dr = com.ExecuteReader();
}
File.Delete(upload);
Response.Write("Upload Successfull!");
}
protected bool CreateUser(string UsersUsername, string UsersPassword)
{
try
{
MembershipUser newUser = System.Web.Security.Membership.CreateUser(UsersUsername, UsersPassword);
Roles.AddUserToRole(UsersUsername, "student");
return true;
}
catch (Exception ex)
{
MessageYo.Text = ex.ToString();
return false;
}
}
}
}

Here's something real simple:
while(dr.Read()) {
string user = dr[0].ToString();
string pass = dr[1].ToString();
if(!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(pass))
CreateUser(user, pass)
}
dr.Close()

I assume that your username and userpassword are in two column. In that case. you can Read a Specific Column of Excel by its specific headers. This is the discussion of this: http://social.msdn.microsoft.com/Forums/en-US/exceldev/thread/6506b0b1-be8c-40f9-879f-21715bd2792e. Then you can pass the values to the function.
A workaround for this: go through XML file which means convert Excel to XML, and then get data from xml to function.

Related

Simple C# connection to .accdb file

All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated
When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.
label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null

Retrieve data from SQL Server database using ajax method C#

I'm new to C# and javacript. I'm doing my first program on Visual Studio and I have one problem to retrieve data from a SQL Server database.
I want to retrieve data from SQL Server and convert it to Json by using an ajax method. But when I start my web page I can see only the table empty, so I think I have not a good method to connect to my data base.
Here is the code for my WebMethod used to retrieve data and convert to Json:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using Newtonsoft.Json;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string LoadData()
{
string strcon = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("select * from kit", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return JsonConvert.SerializeObject(ds.Tables[0]);
}
Please I need your Help I have done several days on this program. Thanks for all your help.
Your CommandType should be Text and not StoredProcedure since you are using a string SQL command and not a Stored Procedure.

Why am I getting a CS1502 (invalid arguments) error from this code?

I'm facing this issue and I don't know the reason behind it. Here's the error Visual Studio is reporting:
The best overloaded method match for 'PostForum.INSERTforum(int, string, string, System.DateTime)' has some invalid arguments
I'm using Oracle to store my data and also created a procedure called INSERTFORUM. I am not sure if I have a problem with the stored procedure or something else. Please help me sort out this issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Forum : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string course_Id = DropDownList1.Text;
int ccourse_Id = Convert.ToInt32(course_Id);
string question = TextBox1.Text;
string posterName = TextBox2.Text;
DateTime blog_date = DateTime.Now;
PostForum.INSERTforum(course_Id, question, posterName, blog_date);
}
}
Code for :Postforum.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public class PostForum
{
public static int INSERTforum(int course_Id, string question, string posterName, DateTime blog_date)
{
int rowsAffected = 0;
using (SqlConnection connection = ConnectionManager.GetDatabaseConnection())
{
SqlCommand command = new SqlCommand("INSERTforum", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#course_Id", SqlDbType.Int).Value = course_Id;
command.Parameters.Add("#question", SqlDbType.VarChar).Value = question;
command.Parameters.Add("#posterName", SqlDbType.VarChar).Value = posterName;
command.Parameters.Add("#blog_date", SqlDbType.DateTime).Value = blog_date;
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
}
}
INSERTforum expects an int as the first parameter. You're passing it a string. Correct your invocation of INSERTforum to read:
PostForum.INSERTforum(ccourse_Id, question, posterName, blog_date);
Note that this will fail if DropDownList1.Text can't be parsed as an integer.
Don't forget to look at the Error List tab in Visual Studio. The error you saw was only the first - the next error would have given you the information I did.

Unable to read data from data layer

I was doing a basic example of 3 tier architecture in c#.I created two dll's for data and business layer.Also I am using data layer dll in business layer code.And,business dll and data access dll in presentation layer(which is a winform application).Now,when the presentation layer code is being executed,an exception is coming which says :
Database
'D:\11feb\practice\3tier\PresentationLayer\PresentationLayer\bin\Debug\Data.mdf'
do not exists.
I had created my database Data.mdf in data layer.
I copied the database files to the location mentioned in exception and the application successfully got executed.But I want the database to be accessed from my data layer.
Data Layer Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DataAccessLayer
{
public class DataAccess
{
public DataTable dataRead()
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Data.mdf;Database=Data;Integrated Security=True;User Instance=True");
DataTable dt = new DataTable();
con.Open();
SqlCommand cmd = new SqlCommand("select ID,Name from datatable", con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}
}
Business Layer Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataAccessLayer;
using System.Data;
namespace BusinessLogicLayer
{
public class BusinessLogic
{
DataAccess dataAccess = new DataAccess();
public DataTable getPersons()
{
try
{
return dataAccess.dataRead();
}
catch { throw; }
}
}
}
Presentation Layer Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BusinessLogicLayer;
namespace PresentationLayer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
BusinessLogic BusinessLogic = new BusinessLogic();
this.dataGridView1.DataSource = BusinessLogic.getPersons();
}
catch
{
MessageBox.Show("Error Occurred");
}
}
}
}
The problem is that you have added Data.mdf in the solution but when the application runs, it tries to find out the mdf file in the bin directory. Click on Data.mdf file in the solution. Go to its properties ( By Pressing F4) and then look out for the property "Copy to the Output Directory" and then change the value to Copy Always.
Also check out your connection string.

Importing Excel sheet into SQL Server with C#

I am working on writing a simple program to import an excel sheet into my database but I am running into an error of:
Could not find installable ISAM
I am not sure what this means and after hours of searching with so many different topics I have turned to SO. There is a lot of talk of Jet and ACE where I am not sure what the difference is but here is the rundown: I have an excel file called test or test1 and I just want to import the first sheet in the file. here is my source code so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string filePath = null;
public Form1()
{
InitializeComponent();
}
//Method to check database connection
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=SSPI;";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
//Method to select a file
private void button2_Click(object sender, EventArgs e)
{
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=Excel 12.0,HDR=Yes;IMEX=1";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open(); //HERE IS WHERE THE ERROR IS
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Table";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Data Exoprted To Sql Server Succefully");
}
}
}
}
}
}
Am I approaching this in the right manor?
You need to wrap Extended Properties part of the connection string in the quotation marks:
// here and here
// --> v v
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=""Excel 12.0,HDR=Yes;IMEX=1""";
The Office oledb driver is probably not installed on your computer. You should download it from microsoft website. After the installation, your code should run.
If you are reading office 2007 (or newer) excel files then I will suggest to use Open source library Epplus to read the excel file.It is purely .NET library and you wont be dependent on oledb driver.
epplus
EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx).
you can easily read an excel file into datatable using this library. have a look at this thread
How convert stream excel file to datatable C#?

Categories

Resources