C# Convert MS Excel column to utf-8 and then to base64 - excel

I have a situation where I have to convert excel single column to utf-8 and then to base64. I have gone through several post which suggests how to read excel file.
Reading Excel files from C#
But I am not sure that in my situation which is the best approach.
I have big files of 2MB.
Kindly suggest me.

I got the solution
using System;
using System.Drawing;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
var myConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\Language_Batch1_OneClick.xls';Extended Properties=Excel 8.0;"); ;
var myCommand = new OleDbCommand();
var upCommand = new OleDbCommand();
int i = 0;
try
{
string sql = null;
myConnection.Open();
myCommand.Connection = myConnection;
sql = "select ANSWER_CODE,Punjabi from [Batch_Lang_1$]";
myCommand.CommandText = sql;
var dataReader = myCommand.ExecuteReader();
while (dataReader.Read())
{
var langText = Convert.ToBase64String(Encoding.UTF8.GetBytes(dataReader["Punjabi"].ToString()));
if (langText.Length >= 1000)
{
continue;
}
var ansCode = dataReader["ANSWER_CODE"].ToString();
sql = "update [Batch_Lang_1$] set Punjabi= '" + langText + "' where ANSWER_CODE='" + ansCode + "'";
upCommand.Connection = myConnection;
upCommand.CommandText = sql;
upCommand.ExecuteNonQuery();
i++;
}
}
}
}

Related

C# Import Excel Data into Existing MDB Database

I have an Access MDB File with just one table simply called "Sheet1". Inside Sheet1 I already have the Fields Identified, but I left the table empty of any records.
I'm trying to copy data from a CSV file into the Access Sheet1 table.
The code below works if the table does not already exist, but I get an error at the AccessCommand.ExecuteNonQuery(); line that says
System.Data.OleDb.OleDbException: Table 'Sheet1' already exists.
How do I revise this code so that I can import the CSV data into an empty Table with Fields already identified?
using System.Data.OleDb;
string filename = "MyCSV.csv";
int result = 0;
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
OleDbConnection AccessConnection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + uploaderMDB);
AccessConnection.Open();
OleDbCommand AccessCommand = new OleDbCommand("SELECT * INTO [Sheet1] FROM [Text;FMT=Delimited;DATABASE=" + dirPath + ";HDR=No].[" + filename + "]", AccessConnection);
AccessCommand.ExecuteNonQuery();
AccessConnection.Close();
Try it this way.
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 System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\your_path_here\Northwind.mdb");
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"INSERT INTO MyExcelTable([Fname], [Lname], [Address])VALUES('" + textBox1.Text + "', '" + textBox2.Text + "','" + textBox3.Text + "')";
cmd.ExecuteNonQuery();
conn.Close();
}
public OleDbConnection myCon { get; set; }
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
I found a solution (it requires XLSX instead though...) for anyone interested. It uses the
Microsoft.Office.Interop.Access reference instead of OleDb.
string filename = "MyXLSX.xlsx";
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "DataBase\\";
string uploaderMDB = dirPath + "MyMDB.mdb";
string fullPath = dirPath + filename;
Application _accessData = new ApplicationClass();
_accessData.Visible = false;
_accessData.OpenCurrentDatabase(uploaderMDB);
_accessData.DoCmd.OpenTable("SHEET1");
_accessData.DoCmd.TransferSpreadsheet(AcDataTransferType.acImport, AcSpreadSheetType.acSpreadsheetTypeExcel12, "Sheet1", fullPath, true, "MY_NAMED_RANGE");
_accessData.CloseCurrentDatabase();
_accessData.Visible = true;
_accessData.Quit(AcQuitOption.acQuitSaveAll);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_accessData);
_accessData = null;

C# How to read ,validate multi tab excel sheet data and import in sql server tables

I need to upload ecommerce catalog data by reading data from multiple tabs And insert those data in SQL server tables.
Whats best way to implement the same using c# and dapper .net and SQL server.
Thanks
Rakesh
Here is sample code i used
using Excel;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Text;
public partial class UserDashboard : BasePage
{
protected void lnkImportExcel_Click(object sender, EventArgs e)
{
try
{
if (!FpdUnConLoanUpload.HasFile)
{
this.DisplayAlert(ref AlertctrlMessage, "Please select an excel (.xlsx) or CSV file.", AlertNotification.Error);
return;
}
if (!FpdUnConLoanUpload.FileName.Trim().ToLower().Split('.')[1].Equals("xlsx") && !FpdUnConLoanUpload.FileName.Trim().ToLower().Split('.')[1].Equals("csv"))
{
this.DisplayAlert(ref AlertctrlMessage, "Please select a valid excel (.xlsx) or CSV file.", AlertNotification.Error);
return;
}
Guid nimgGUID = Guid.NewGuid();
if (!FpdUnConLoanUpload.FileName.Trim().ToLower().Equals(""))
{
if (FpdUnConLoanUpload.FileName.Trim().ToLower().Split('.')[1].Equals("xlsx"))
{
IExcelDataReader iExcelDataReader = null;
string TargetPathFileSave = Server.MapPath(ConfigurationManager.AppSettings.Get("ImportFiles"));
TargetPathFileSave = TargetPathFileSave + "\\";
if (!System.IO.Directory.Exists(TargetPathFileSave))
{
System.IO.Directory.CreateDirectory(TargetPathFileSave);
}
TargetPathFileSave = TargetPathFileSave + "\\" + nimgGUID.ToString().Trim() + FpdUnConLoanUpload.FileName.Substring(FpdUnConLoanUpload.FileName.LastIndexOf('.')).ToLower();
FpdUnConLoanUpload.PostedFile.SaveAs(TargetPathFileSave);
FileStream oStream = File.Open(TargetPathFileSave, FileMode.Open, FileAccess.Read);
DataSet dsUnUpdated = new DataSet();
if (FpdUnConLoanUpload.FileName.Trim().ToLower().Split('.')[1].Equals("xlsx"))
{
iExcelDataReader = ExcelReaderFactory.CreateOpenXmlReader(oStream);
iExcelDataReader.IsFirstRowAsColumnNames = true;
dsUnUpdated = iExcelDataReader.AsDataSet();
iExcelDataReader.Close();
}
if (dsUnUpdated != null)
{
Session["dsUnUpdated"] = dsUnUpdated;
LinkProcess.Visible = true;
grdSearchData.DataSource = dsUnUpdated;
grdSearchData.DataBind();
}
else
{
this.DisplayAlert(ref AlertctrlMessage, "No Data Found In File!", AlertNotification.Error);
}
}
catch (Exception exc)
{
lblcount.Text = "";
this.DisplayAlert(ref AlertctrlMessage, exc.Message, AlertNotification.Error);
}
}
}
}
now in filled dataset ds you will have all data as per sheets as data table
traverse data tables in ds and save them to db

Exporting from gridview to excel is not showing long numbers

Hello I'm trying to export my data from a gridview to excel the problem is I have a nvarchar column the have the following barcode: 00373228210001695726 and in excel after export it looks like this 3,73228E+17
my query looks like this:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=AP;Initial Catalog=MGW;User Id=sa;Password=GaUbdFO2;App=EntityFramework;");
try
{
connection.Open();
string sqlStatement = " ";
sqlStatement += " SELECT UserName AS UserID, Site, AddressID, Parameters, Content AS Barcode , TriggerDate, ReceivedDate, Action, DeviceID, Longitude, Latitude, CASE WHEN Latitude != '' THEN 'View Map Location' Else 'No Location' END AS LatitudeMSG FROM RequestWithLocation WHERE";
sqlStatement += " Content = #Content ";
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlStatement += " AND TriggerDate >= #TriggerDateStart AND TriggerDate <= #TriggerDateEnd ";
}
sqlStatement += " ORDER BY TriggerDate DESC";
using (SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection))
{
sqlCmd.Parameters.AddWithValue("#Content", TextBoxSearch.Text);
if (!string.IsNullOrWhiteSpace(TextBoxStart.Text) && !string.IsNullOrWhiteSpace(TextBoxEnd.Text))
{
sqlCmd.Parameters.AddWithValue("#TriggerDateStart", Convert.ToDateTime(TextBoxStart.Text));
sqlCmd.Parameters.AddWithValue("#TriggerDateEnd", Convert.ToDateTime(TextBoxEnd.Text).AddDays(+1));
}
using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
{
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
GridDisplayData.DataSource = dt;
GridDisplayData.DataBind();
lblError.Text = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('No data found');", true);
}
}
}
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Search timed-out! try again..');", true);
}
EXPORT FUNCTION
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachchment; filename=Report_EventScan.xls; IMEX=1;");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridDisplayData.RenderControl(hw);
//Panel7.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
Use Response.Write("'" + sw.ToString()); to force a prefixed single quotation character in front of the number. That forces Excel to adopt text formatting.
(I'm assuming that + is a string concatenation in your language; it might be &).
I solved my problem. this is what I did:
You can download the EPPlus Excel reader from here http://epplus.codeplex.com/
Then using OfficeOpenXml; on top of your project and the following code to your export button, this should work for everyone who use a DataSet which is saved in a ViewState
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
DataSet dt = new DataSet();
dt = (DataSet)ViewState["QueryTable"];
MemoryStream ms = new MemoryStream();
int i = 1;
using (ExcelPackage package = new ExcelPackage(ms))
{
foreach (DataTable table in dt.Tables)
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("My Excel Report " + i++);
worksheet.Cells["A1"].LoadFromDataTable(table, true);
}
Response.Clear();
package.SaveAs(Response.OutputStream);
Response.AddHeader("content-disposition", "attachchment; filename= test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
Response.End();
}
}

How to get Firefox history using C# application?

I need to retrieve the Firefox history(url) using C# windows Form application.
I am Using Firefox 17.0.1 version.
I have been tried with DDEClient class and SQLLite database. both are not working.
When I use the DDEClient class I can able to get the active tab URL from the Firefox, when I use the SQLLite Database, it is not working VS2010.
How can I achieve this requirement?
private static Logger logger = LogManager.GetCurrentClassLogger();
private static string dbName = "places.sqlite";
private static int dbColumnUrl = 1;
private static int dbColumnVisitDate = 9;
String strConnection = #"Data Source=" + newPath + #";Version=3;";
using (SQLiteConnection connection = new SQLiteConnection(strConnection))
{
string query = "select * from moz_places;";
using (SQLiteCommand cmd = new SQLiteCommand(query, connection))
{
connection.Open();
using (SQLiteDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
logger.Info("time: " + dr.GetValue(dbColumnVisitDate));
logger.Info("URL: " + dr.GetValue(dbColumnUrl));
}
}
}
}

C# create configuration file

This code How can I create configuration file if so that i can change connection string easy
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 MySql.Data.MySqlClient;
using System.Web;
using mshtml;
namespace tabcontrolweb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string MyConString = "SERVER=192.168.0.78;" +
"DATABASE=webboard;" +
"UID=aimja;" +
"PASSWORD=aimjawork;" +
"charset=utf8;";
MySqlConnection connection = new MySqlConnection(MyConString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = "SELECT urlwebboard FROM `listweb` WHERE `urlwebboard` IS NOT NULL AND ( `webbordkind` = 'เว็บท้องถิ่น' ) and `nourl`= 'n' order by province, amphore limit 4 ";
connection.Open();
Reader = command.ExecuteReader();
string[] urls = new string[4];
string thisrow = "";
string sumthisrow = "";
while (Reader.Read())
{
thisrow = "";
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
System.IO.File.AppendAllText(#"C:\file.txt", thisrow + " " + Environment.NewLine);
sumthisrow = Reader.GetValue(Reader.FieldCount - 1).ToString();
}
for (int m = 0; m < 4 ; m++)
{
urls[m] = sumthisrow;
MessageBox.Show(urls[m]);
}
webBrowser1.Navigate(new Uri(urls[0]));
webBrowser1.Dock = DockStyle.Fill;
webBrowser2.Navigate(new Uri(urls[1]));
webBrowser2.Dock = DockStyle.Fill;
webBrowser3.Navigate(new Uri(urls[2]));
webBrowser3.Dock = DockStyle.Fill;
webBrowser4.Navigate(new Uri(urls[3]));
webBrowser4.Dock = DockStyle.Fill;
}
connection.Close();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//if (webBrowser1.Document != null)
//{
// IHTMLDocument2 document = webBrowser1.Document.DomDocument as IHTMLDocument2;
// if (document != null)
// {
// IHTMLSelectionObject currentSelection = document.selection;
// IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
// if (range != null)
// {
// const String search = "We";
// if (range.findText(search, search.Length, 2))
// {
// range.select();
// }
// }
// }
//}
}
}
}
You can create an XML configuration file looking like this :
<db-config>
<server>192.168.0.78</server>
<database>webboard</database>
<...>...</...>
</db-config>
Then, use XMLTextReader to parse it.
Here is a basic example of how you can use it to parse XML files :
using System;
using System.Xml;
namespace ReadXMLfromFile
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
XmlTextReader reader = new XmlTextReader ("books.xml");
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType.EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
Console.ReadLine();
}
}
}
Hint : Use the ReadTofollowing() to get your values.
Once your XML DB Config Reader class is done, you use it each time you need a new connection, and you'll only need to change your DB Config XML file to change your DB Connections configuration.
Edit : there is an interesting article about Storing database connection settings in .NET here.
Use the default
System.Configuration.ConfigurationManager
that C# supports!
See: http://msdn.microsoft.com/en-us/library/bb397750.aspx

Resources