I want to import data to gridview from Excel. And I have done using System.Data.OleDb as
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dtExcelRecords = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dtExcelRecords);
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
How to achieve the same using LinqToExcel
Try this
if (ExlSheet.HasFile)
{
string fileName = Path.GetFileName(ExlSheet.PostedFile.FileName);
string fileExtension = Path.GetExtension(ExlSheet.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
ExlSheet.SaveAs(fileLocation);
ExcelQueryFactory excelFile = new ExcelQueryFactory(fileLocation);
var data = from a in excelFile.Worksheet("Sheet1") select a;
var columnNames = excelFile.GetColumnNames("Sheet1");
DataTable dtExcelRecords = new DataTable();
foreach (var columnName in columnNames)
{
dtExcelRecords.Columns.Add(columnName);
}
foreach (var row in data)
{
DataRow dr = dtExcelRecords.NewRow();
foreach (var columnName in columnNames)
{
dr[columnName] = row[columnName];
}
dtExcelRecords.Rows.Add(dr);
}
gv.DataSource = dtExcelRecords;
gv.DataBind();
}
Related
My code below gives me the following error as i typed in the title
What am I doing wrong here?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
conn = new OleDbConnection(pathConn);
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
spreadSheetData starts falling null
my codes refer to Excel to DataGridView
1st answered by JohnG
and this video https://www.youtube.com/watch?v=CfNMPDJVjPI
Thanks for any help!
Your code should be something like this:
I have encapsulated your connection inside a using, so we are sure freeing resources. Also it's necessary to open the connection.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Prepare things
using(OleDbConnection conn = new OleDbConnection(pathConn))
{
conn.Open(); //Added this line
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
//Do staff
}
}
}
You must open your connection before using it :
conn = new OleDbConnection(pathConn);
conn.Open();
You should also use the "Using" statement to properly dispose the connection when not used anymore.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string huru = openFileDialog1.FileName;
this.textBox1.Text = huru;
string pathConn;
//OleDbConnection conn;
DataTable spreadSheetData;
string sheetName = "";
OleDbCommand onlineConnection;
OleDbDataAdapter myDataAdapter;
DataTable dt = new DataTable();
if (huru.Substring(huru.Length - 3) == "lsx")
{
pathConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + huru
+ ";Extended Properties = \"Excel 12.0 Xml;HDR=YES\"; ";
}
else
{
pathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + huru
+ ";Extended Properties=\"Excel 8.0;HDR=yes;\";";
}
using(OleDbConnection conn = ew OleDbConnection(pathConn))
{
//conn = new OleDbConnection(pathConn);
conn.Open();
spreadSheetData = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in spreadSheetData.Rows)
{
sheetName = dr["TABLE_NAME"].ToString();
sheetName = sheetName.Replace("'", "");
if (sheetName.EndsWith("$"))
{
onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", conn);
myDataAdapter = new OleDbDataAdapter(onlineConnection);
dt = new DataTable();
dt.TableName = sheetName;
myDataAdapter.Fill(dt);
ds.Tables.Add(dt);
}
}
}
}
I have radio buttons from which I can select the type of data source to retrieve the email addresses of recipients.
if (RadioButton1.Checked)
{
sql.Open();
string s = "select * from address";
SqlCommand t = new SqlCommand(s, sql);
t.ExecuteNonQuery();
sql.Close();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT address FROM address1";
cmd.Connection = sql;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
sql.Open();
da.Fill(dt);
sql.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
else if (RadioButton2.Checked)
{
string connectionString = "";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dt);
con.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
}
else if (RadioButton3.Checked)
{
if (FileUpload2.HasFile)
{
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload2.SaveAs(fileLocation);
StreamReader sr = new StreamReader(fileLocation);
String line = sr.ReadToEnd();
string[] toAddressArray;
toAddressArray = line.Split(new char[] { ' ' });
foreach (string a in toAddressArray)
{
Msg.To.Add(a);
}
}
}
Now, what I want is when the recipient clicks the link in the html page which I have sent as mail body, I want to retrieve the mail id of the recipient which is from one of the three radio button data source options.
How to get the mail id?
Here is the complete code:
SqlConnection sql = new SqlConnection(ConfigurationManager.ConnectionStrings["mystring"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
getFiles();
if (!IsPostBack)
{
var list = getFiles();
dd1.DataSource = list;
dd1.DataTextField = "Key";
dd1.DataValueField = "Value";
dd1.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
SendHTMLMail();
}
void SendHTMLMail()
{
StreamReader reader = new StreamReader(dd1.SelectedItem.Value);
string readFile = reader.ReadToEnd();
Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\#\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
string output = regx.ToString();
string count = 0.ToString();
output = readFile;
string username = Server.UrlEncode(this.txtUsername.Text);
output = regx.Replace(output, new MatchEvaluator((match) =>
{
var url = Uri.EscapeDataString(match.Value.ToString());
return $"http://localhost:61187/two?sender={username}&link={url}&count={count}";
}));
MailMessage Msg = new MailMessage();
Msg.From = new MailAddress(txtUsername.Text);
Msg.Subject = txtSubject.Text;
Msg.Body = output.ToString();
Msg.IsBodyHtml = true;
if (fuAttachment.HasFile)
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
Msg.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
if (RadioButton1.Checked)
{
sql.Open();
string s = "select * from address";
SqlCommand t = new SqlCommand(s, sql);
t.ExecuteNonQuery();
sql.Close();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT address FROM address1";
cmd.Connection = sql;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
sql.Open();
da.Fill(dt);
sql.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
else if (RadioButton2.Checked)
{
string connectionString = "";
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload1.SaveAs(fileLocation);
if (fileExtension == ".xls")
{
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (fileExtension == ".xlsx")
{
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection con = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
dAdapter.SelectCommand = cmd;
dAdapter.Fill(dt);
con.Close();
foreach (DataRow row in dt.Rows)
{
Msg.To.Add(row["address"].ToString());
}
}
}
else if (RadioButton3.Checked)
{
if (FileUpload2.HasFile)
{
string fileName = Path.GetFileName(FileUpload2.PostedFile.FileName);
string fileLocation = Server.MapPath("~/App_Data/" + fileName);
FileUpload2.SaveAs(fileLocation);
StreamReader sr = new StreamReader(fileLocation);
String line = sr.ReadToEnd();
string[] toAddressArray;
toAddressArray = line.Split(new char[] { ' ' });
foreach (string a in toAddressArray)
{
Msg.To.Add(a);
}
}
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
smtp.EnableSsl = true;
smtp.Send(Msg);
Msg = null;
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
}
public List<KeyValuePair<string, string>> getFiles()
{
DirectoryInfo di = new DirectoryInfo(HostingEnvironment.MapPath("/App_Data"));
var fi = di.EnumerateFiles("*.html", SearchOption.TopDirectoryOnly);
var files = new List<KeyValuePair<string, string>>();
foreach (FileInfo file in fi)
{
files.Add(new KeyValuePair<string, string>(file.Name, file.FullName));
}
return files;
}
I am reading excel sheet using below code but that gives blank data table.
public static DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xlsx") == 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con); //here we read data from sheet1
oleAdpt.Fill(dtexcel); //fill excel data into dataTable
}
catch(Exception ex) { }
}
return dtexcel;
}
It displays empty data table as below screenshot.
you forgot few things, like OleDbConnection.Open(); and using OleDbCommand
public DataTable ReadExcel(string fileName)
{
string fileExt = ".xlsx";
string sheetName = "Sheet1$";
string conn = string.Empty;
DataTable dt = new DataTable();
if (fileExt.CompareTo(".xlsx") != 0)
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';"; //for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0 Xml;HDR=YES';"; //for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
using ( OleDbCommand cmd = new OleDbCommand())
{
con.Open();
try
{
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM [" + sheetName + "]";
dt.TableName = sheetName;
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
da.Fill(dt);
}
}
catch (Exception ex) { }
}
return dt;
}
try rhis code hope it help you
protected void btn_Click(object sender, EventArgs e)
{
string filename = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("File/" + filename));
string CurrentFilePath = Server.MapPath("File/" + filename);
string connectString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + CurrentFilePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
conn.Open();
DataTable Sheets = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
foreach (DataRow dr in Sheets.Rows)
{
string sht = dr[2].ToString().Replace("'", "");
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [" + sht + "]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
}
}
For me working following code
string filePath = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "").Replace("\\bin\\Release", "");
string fileLocation = filePath + ConfigurationManager.AppSettings["EmployeeDetailsFilePath"];
Stream inputStream = File.Open(fileLocation, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(inputStream);
reader.IsFirstRowAsColumnNames = true;
DataSet dataSet = reader.AsDataSet();
inputStream.Dispose();
reader.Dispose();
here must add reference of ExcelDataReader dll in your project.
My excel file is that column1A: city,ankara,ankara,ankara,istanbul,istanbul,izmir
I want to that combobox looks like ankara,istanbul,izmir
it doesn't again.
OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");
baglan.Open();
string sql = "Select * From [Sayfa1$A1:A100] ";
OleDbCommand komut = new OleDbCommand(sql, baglan);
OleDbDataReader dr = null;
dr = komut.ExecuteReader();
while (dr.Read())
{
if (dr[0] != "")
{
combobox1.Items.Add(dr[0].ToString());
}
else
{
break;
}
}
baglan.Close();
if (dr[0] != ""){
if(!combobox1.Items.Contains(dr[0])){
combobox1.Items.Add(dr[0].ToString());
}
}
Try this:
OleDbConnection baglan = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0");
baglan.Open();
string sql = "Select * From [Sayfa1$A1:A100] ";
OleDbCommand komut = new OleDbCommand(sql, baglan);
OleDbDataReader dr = null;
dr = komut.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
// To Copy distinct values from specified column to a different datatable
DataTable diffValues = dt.DefaultView.ToTable(true, "ColName");
combobox1.DataSource = datatable;
It works for me.
I have one excel sheet from which I am getting data in dataset using OleDbConnection
private static DataSet ImportExcel(string FileName, bool hasHeaders)
{
string HDR = hasHeaders ? "Yes" : "No";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileName +
";Extended Properties=\"Excel 8.0;HDR=" + HDR + ";IMEX=1\"";
DataSet output = new DataSet();
using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
foreach (DataRow row in dt.Rows)
{
string sheet = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheet + "]", conn);
cmd.CommandType = CommandType.Text;
DataTable outputTable = new DataTable(sheet);
output.Tables.Add(outputTable);
new OleDbDataAdapter(cmd).Fill(outputTable);
}
}
return output;
}
Now I want to Insert data from this dataset to sqlite table.
This is how we can do it
SQLiteConnection m_dbConnection;
void createDbAndTable()
{
SQLiteConnection.CreateFile("MyDatabase.sqlite");
m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;");
m_dbConnection.Open();
string sql = "create table myValues (name varchar(20), highScore int)";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
void fillTable(DataSet ds)
{
var dt = ds.Tables[0];
foreach (DataRow dr in dt.Rows)
{
var name = dr["name"].ToString();
var score = Convert.ToInt32(dr["value"].ToString());
string sql = "insert into myValues (name, highScore) values ( '" + name + "'," + score + ")";
SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();
}
m_dbConnection.Close();
}