Calculate Excel value before import to SQL Server - c#

I have problem about import to SQL Server, the scenario is to import excel file and calculate the value in column 3 and 4 (produce column 5) of the imported excel file. In my case, the calculation is in C#, not in excel. And then import to SQL Server (ASP.Net + C#). Any idea how to do this ?
This is my code (it's still give me error)
protected void btnImport_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
if (Extension == ".xlsx")
{
string path = string.Concat((Server.MapPath("~/tampung/" + FileUpload1.FileName)));
FileUpload1.PostedFile.SaveAs(path);
//make connection to excel workBook
using (OleDbConnection oledbcon = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;"))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Sheet1$]", oledbcon);
OleDbDataAdapter ObjAdapter1 = new OleDbDataAdapter(cmd);
oledbcon.Open();
using (DbDataReader dr = cmd.ExecuteReader())
{
DataTable DT = new DataTable();
DT.Load(dr);
for (int i = 0; i < DT.Rows.Count; i++)
{
string Year = DT.Rows[i][0].ToString();
string StudentName = DT.Rows[i][1].ToString();
string Semester = DT.Rows[i][2].ToString();
decimal Value1 = Convert.ToDecimal(DT.Rows[i][3]);
decimal Value2 = Convert.ToDecimal(DT.Rows[i][4]);
decimal AverageValue = Convert.ToDecimal((Value1 + Value2) / 2);
}
string conString = #"Data Source=PETRELLI;Initial Catalog=demo;Integrated Security=True";
SqlBulkCopy bulkInsert = new SqlBulkCopy(conString);
bulkInsert.DestinationTableName = "student";
bulkInsert.WriteToServer(dr);
oledbcon.Close();
Array.ForEach(Directory.GetFiles(Server.MapPath("~/temp/")), File.Delete);
Label1.Text = "Succeeded";
}
}
}
else
{
Label1.Text = "Hi, it's error";
}
}
else
{
Label1.Text = "Please choose the right file excel";
}
}

The error should be coming from this line
bulkInsert.WriteToServer(dr);
This is happening because DT.Load(dr), that you called earlier, have looped through the dr already and has moved the pointer to the end, after which you can not use the dr again.
DT.Load(dr); //<-- this line already looped through the dr. dr can't be used after this line
Solution
Use the DT instead of dr since you already have DT populated with the required data by calling DT.Load(dr)

Related

c# provider for excel not registered

For some projects I need the options of exporting and importing from/to an Excel.
For that I'm using that code:
private void myButton12_Click(object sender, EventArgs e)
{
string path = string.Empty;
string ext = string.Empty;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = file.FileName;
ext = System.IO.Path.GetExtension(path);
if(ext == ".xls" || ext == ".xlsx")
{
Console.WriteLine("ok");
DataTable dt = new DataTable();
dt = ReadExcel(path, ext);
dataGridView13.DataSource = dt;
}
}
}
public DataTable ReadExcel(string fileName, string fileExt)
{
string conn = string.Empty;
DataTable dtexcel = new DataTable();
if (fileExt.CompareTo(".xls") == 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 16.0;HDR=NO';"; //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 e)
{
Console.WriteLine(e);
}
}
return dtexcel;
}
Problem is that I get that Exception:
The provider 'Microsoft.ACE.OLEDB.12.0' is not registered on the local computer.
After looking on the internet, I seems like it come from the x86 configuration need that I tried... I've also tried switching for some others, but none of them worked,
I really can't find any solution to my problem,
Any idea where the problem can be?
Thanks
If you run your app in X64 Target CPU you need "AccessDatabaseEngine_X64.exe" , if you run your app in X86 you need "AccessDatabaseEngine.exe" fromthe page below :
https://www.microsoft.com/en-us/download/details.aspx?id=13255

How do you programmatically check if a spreadsheet has headers in C#

I am creating a winform application where every day, a user will select a xlsx file with the day's shipping information to be merged with our invoicing data.
The challenge I am having is when the user does not download the xlsx file with the specification that the winform data requires. (I wish I could eliminate this step with an API connection but sadly I cannot)
My first step is checking to see if the xlsx file has headers to that my file path is valid
Example
string connString = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + *path* + "';Extended Properties='Excel 12.0;HDR=YES;';";
Where path is returned from an OpenFileDialog box
If the file was chosen wasn't downloaded with headers the statement above throws an exception.
If change HDR=YES; to HDR=NO; then I have trouble identifying the columns I need and if the User bothered to include the correct ones.
My code then tries to load the data into a DataTable
private void loadRows()
{
for (int i = 0; i < deliveryTable.Rows.Count; i++)
{
DataRow dr = deliveryTable.Rows[i];
int deliveryId = 0;
bool result = int.TryParse(dr[0].ToString(), out deliveryId);
if (deliveryId > 1 && !Deliveries.ContainsKey(deliveryId))
{
var delivery = new Delivery(deliveryId)
{
SalesOrg = Convert.ToInt32(dr[8]),
SoldTo = Convert.ToInt32(dr[9]),
SoldName = dr[10].ToString(),
ShipTo = Convert.ToInt32(dr[11]),
ShipName = dr[12].ToString(),
};
Which all works only if the columns are in the right place.
If they are not in the right place my thought is to display a message to the user to get the right information
Does anyone have any suggestions?
(Sorry, first time posting a question and still learning to think through it)
I guess you're loading the spreadsheet into a Datatable? Hard to tell with one line of code. I would use the columns collection in the datatable and check to see if all the columns you want are there. Sample code to enumerate the columns below.
private void PrintValues(DataTable table)
{
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
private void GetExcelSheetForUpload(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
if (grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE")
{
GetExcelSheetForEmpl(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!... Upload Excel Sheet in header Defined Format ";
}

Uploading an Excel sheet and importing the data into SQL Server database

I am developing this simple application to upload an Excel file (.xlsx) and import the data present in that Excel worksheet into a SQL Server Express database in .NET
I'm using the following code on click of the import button after browsing and selecting the file to do it.
protected void Button1_Click(object sender, EventArgs e)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
//file upload path
string path = FileUpload1.PostedFile.FileName;
//string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
//Create connection string to Excel work book
string excelConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
}
But the code doesn't run when I use
string path = FileUpload1.PostedFile.FileName;`
and even
string path="C:\ Users\ Hemant\Documents\example.xlsx";`
The dReader is unable to take the path in this format.
It is only able to take path in the following format
string path="C:\\ Users\\ Hemant\\Documents\\example.xlsx";
i.e. with the the \\ in the path.For which I have to hard code the path but we have to browse the file.
So,can any one please suggest a solution to use the path taken by the FileUpload1 to import the data?
You are dealing with a HttpPostedFile; this is the file that is "uploaded" to the web server. You really need to save that file somewhere and then use it, because...
...in your instance, it just so happens to be that you are hosting your website on the same machine the file resides, so the path is accessible. As soon as you deploy your site to a different machine, your code isn't going to work.
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
Not sure why the file path is not working, I have some similar code that works fine.
But if with two "\" it works, you can always do path = path.Replace(#"\", #"\\");
You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)
Example:
private static void DataReaderBulkCopySample()
{
using (var reader = new ExcelDataReader(#"test.xlsx"))
{
var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);
using (var bulkCopy = new SqlBulkCopy(ConnectionString))
{
// MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess,
// optimizing memory usage by using the IDataReader streaming capabilities
bulkCopy.EnableStreaming = true;
bulkCopy.DestinationTableName = TableName;
foreach (var col in cols)
bulkCopy.ColumnMappings.Add(col, col);
bulkCopy.WriteToServer(reader);
}
}
}
Try Using
string filename = Path.GetFileName(FileUploadControl.FileName);
Then Save the file at specified location using:
FileUploadControl.PostedFile.SaveAs(strpath + filename);
public async Task<HttpResponseMessage> PostFormDataAsync() //async is used for defining an asynchronous method
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var fileLocation = "";
string root = HttpContext.Current.Server.MapPath("~/App_Data");
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(root); //Helps in HTML file uploads to write data to File Stream
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName); //Gets the file name
var filePath = file.Headers.ContentDisposition.FileName.Substring(1, file.Headers.ContentDisposition.FileName.Length - 2); //File name without the path
File.Copy(file.LocalFileName, file.LocalFileName + filePath); //Save a copy for reading it
fileLocation = file.LocalFileName + filePath; //Complete file location
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, recordStatus);
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
public void ReadFromExcel()
{
try
{
DataTable sheet1 = new DataTable();
OleDbConnectionStringBuilder csbuilder = new OleDbConnectionStringBuilder();
csbuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
csbuilder.DataSource = fileLocation;
csbuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
string selectSql = #"SELECT * FROM [Sheet1$]";
using (OleDbConnection connection = new OleDbConnection(csbuilder.ConnectionString))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(selectSql, connection))
{
connection.Open();
adapter.Fill(sheet1);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
A proposed solution will be:
protected void Button1_Click(object sender, EventArgs e)
{
try
{
CreateXMLFile();
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("bulk_in", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#account_det", sw_XmlString.ToString ());
int i= cmd.ExecuteNonQuery();
if(i>0)
{
Label1.Text = "File Upload successfully";
}
else
{
Label1.Text = "File Upload unsuccessfully";
return;
}
con.Close();
}
catch(SqlException ex)
{
Label1.Text = ex.Message.ToString();
}
}
public void CreateXMLFile()
{
try
{
M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
fileExtn = Path.GetExtension(M_Filepath);
strGuid = System.Guid.NewGuid().ToString();
fNameArray = M_Filepath.Split('.');
fName = fNameArray[0];
xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
fileName = xlRptName.Trim() + fileExtn.Trim() ;
FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);
strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
{
Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
}
FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
if (strFileName == "DEMO.XLS")
{
strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
}
if (strFileName == "DEMO.XLSX")
{
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";
}
strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";
OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);
mydata.TableMappings.Add("Table", "arul");
mydata.Fill(dsExcl);
dsExcl.DataSetName = "DocumentElement";
intRowCnt = dsExcl.Tables[0].Rows.Count;
intColCnt = dsExcl.Tables[0].Rows.Count;
if(intRowCnt <1)
{
Label1.Text = "No records in Excel File";
return;
}
if (dsExcl==null)
{
}
else
if(dsExcl.Tables[0].Rows.Count >= 1000 )
{
Label1.Text = "Excel data must be in less than 1000 ";
}
for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
{
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
}
if (strValid == "")
{
Label1.Text = "Name should not be empty";
return;
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
}
if (strValid == "")
{
Label1.Text = "Mobile_num should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
}
if (strValid == "")
{
Label1.Text = "Account_number should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
}
if (strValid == "")
{
Label1.Text = "Amount should not be empty";
}
else
{
strValid = "";
}
if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
{
strValid = "";
}
else
{
strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
}
if (strValid == "")
{
Label1.Text = "date_a2 should not be empty";
}
else
{
strValid = "";
}
}
}
catch
{
}
try
{
if(dsExcl.Tables[0].Rows.Count >0)
{
dr = dsExcl.Tables[0].Rows[0];
}
dsExcl.Tables[0].TableName = "arul";
dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);
}
catch
{
}
}`enter code here`
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
protected void Button1_Click(object sender, EventArgs e)
{
//Upload and save the file
string excelPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(excelPath);
string conString = string.Empty;
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
switch (extension)
{
case ".xls": //Excel 97-03
conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx": //Excel 07 or higher
conString = ConfigurationManager.ConnectionStrings["Excel07+ConString"].ConnectionString;
break;
}
conString = string.Format(conString, excelPath);
using (OleDbConnection excel_con = new OleDbConnection(conString))
{
excel_con.Open();
string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString();
DataTable dtExcelData = new DataTable();
//[OPTIONAL]: It is recommended as otherwise the data will be considered as String by default.
dtExcelData.Columns.AddRange(new DataColumn[2] { new DataColumn("Id", typeof(int)),
new DataColumn("Name", typeof(string)) });
using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con))
{
oda.Fill(dtExcelData);
}
excel_con.Close();
string consString = ConfigurationManager.ConnectionStrings["dbcn"].ConnectionString;
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//Set the database table name
sqlBulkCopy.DestinationTableName = "dbo.Table1";
//[OPTIONAL]: Map the Excel columns with that of the database table
sqlBulkCopy.ColumnMappings.Add("Sl", "Id");
sqlBulkCopy.ColumnMappings.Add("Name", "Name");
con.Open();
sqlBulkCopy.WriteToServer(dtExcelData);
con.Close();
}
}
}
}
Copy this in web config
<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
<add name="Excel07+ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'"/>
you can also refer this link : https://athiraji.blogspot.com/2019/03/how-to-upload-excel-fle-to-database.html
protected void btnUpload_Click(object sender, EventArgs e)
{
divStatusMsg.Style.Add("display", "none");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "";
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "DateExcel" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/DateExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/DateExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
if ((grdExcel.HeaderRow.Cells[0].Text.ToString() == "CODE") && grdExcel.HeaderRow.Cells[1].Text.ToString() == "SAL")
{
GetExcelSheetForEmployeeCode(PathName);
}
else
{
divStatusMsg.Style.Add("display", "");
divStatusMsg.Attributes.Add("class", "alert alert-danger alert-dismissable");
divStatusMsg.InnerText = "ERROR !!...Please Upload Excel Sheet in header Defined Format ";
}
}
}
}
private void GetExcelSheetForEmployeeCode(string filename)
{
int count = 0;
int selectedcheckbox = 0;
string empcodeexcel = "";
string empcodegrid = "";
string excelFile = "Employee/DateExcel" + filename;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet ds = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + filename;
// Create connection.
objConn = new OleDbConnection(connString);
// Opens connection with the database.
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
// Get the data table containing the schema guid, and also sheet names.
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
// And respective data will be put into dataset table
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT DISTINCT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(ds, "TABLE");
if (ds.Tables[0].ToString() != null)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
for (int k = 0; k < GrdEmplist.Rows.Count; k++)
{
empcodeexcel = ds.Tables[0].Rows[j][0].ToString();
date.Value = ds.Tables[0].Rows[j][1].ToString();
Label lbl_EmpCode = (Label)GrdEmplist.Rows[k].FindControl("lblGrdCode");
empcodegrid = lbl_Code.Text;
CheckBox chk = (CheckBox)GrdEmplist.Rows[k].FindControl("chkSingle");
TextBox txt_Sal = (TextBox)GrdEmplist.Rows[k].FindControl("txtSal");
if ((empcodegrid == empcodeexcel) && (date.Value != ""))
{
chk.Checked = true;
txt_Sal.Text = date.Value;
selectedcheckbox = selectedcheckbox + 1;
lblSelectedRecord.InnerText = selectedcheckbox.ToString();
count++;
}
if (chk.Checked == true)
{
}
}
}
}
}
i++;
}
}
catch (Exception ex)
{
ShowMessage(ex.Message.ToString(), 0);
}
finally
{
// Clean up.
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "DateExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdExcel.DataSource = dss.Tables[0].DefaultView;
grdExcel.DataBind();
lblTotalRec.InnerText = Convert.ToString(grdExcel.Rows.Count);
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdExcel.DataSource = null;
grdExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
bool logval = true;
if (logval == true)
{
String img_1 = fuUploadExcelName.PostedFile.FileName;
String img_2 = System.IO.Path.GetFileName(img_1);
string extn = System.IO.Path.GetExtension(img_1);
string frstfilenamepart = "";
frstfilenamepart = "Emp" + DateTime.Now.ToString("ddMMyyyyhhmmss"); ;
UploadExcelName.Value = frstfilenamepart + extn;
fuUploadExcelName.SaveAs(Server.MapPath("~/Emp/EmpExcel/") + "/" + UploadExcelName.Value);
string PathName = Server.MapPath("~/Emp/EmpExcel/") + "\\" + UploadExcelName.Value;
GetExcelSheetForEmp(PathName, UploadExcelName.Value);
}
}
}
private void GetExcelSheetForEmp(string PathName, string UploadExcelName)
{
string excelFile = "EmpExcel/" + PathName;
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
DataSet dss = new DataSet();
String connString = "Provider=Microsoft.ACE.OLEDB.12.0;Persist Security Info=True;Extended Properties=Excel 12.0 Xml;Data Source=" + PathName;
objConn = new OleDbConnection(connString);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return;
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
if (i == 0)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + excelSheets[i] + "]", objConn);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
oleda.Fill(dss, "TABLE");
}
i++;
}
grdByExcel.DataSource = dss.Tables[0].DefaultView;
grdByExcel.DataBind();
}
catch (Exception ex)
{
ViewState["Fuletypeidlist"] = "0";
grdByExcel.DataSource = null;
grdByExcel.DataBind();
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}

Dot is implicitly converted into hash while converting data from Excel file to XML

I have succeeded in creating XML file from an Excel file using the following C# code:
protected void Button5_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
OleDbConnection ole = new OleDbConnection();
string s = Server.MapPath("../admin/ProductOptions");
s = s + "\\" + FileUpload1.FileName;
System.IO.File.Delete(s);
FileUpload1.PostedFile.SaveAs(s);
string path = s;
ole.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;" + "\"";
OleDbCommand command = new OleDbCommand("select * from[SHEET1$]", ole);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
GridView1.Visible = true;
string filepath = Server.MapPath("ProductOptions") + "\\" + DDLproduct.SelectedValue + ".xml";
Session["ss"] = ds;
write_to_xml(ds,filepath);
}
else
{
Label2.Visible = true;
Label2.Text="[Please Select a file]";
}
}
But the problem is when this code is converting the Excel Data to XML data, then dots are itself converted into Hash(Only First Row). I know the reason but don't know the solution.
It`s happening because of dots in Excel file when converted into XML tags them implicitly converted to HASH.......
Kindly suggest me, how can I stop this conversion?
Finally got the solution:
When OLEDB Adapter fills the data in DataSet, it converts DOT into HASH.
Now I have stored that data into a DataTable(dt) and then accessed the column name and replace HASH with DOT (using Replace method of String) and create a new DataTable(dt2) with new column names.
After this using two for loops, I have inserted data from first DataTable(dt) to new Datatable(dt2).
(*one loop for rows and another one for columns)
Finally bind the grid with new DataTable(dt2)
Following is the full code for that function:
if (FileUpload1.HasFile)
{
OleDbConnection ole = new OleDbConnection();
string s = Server.MapPath("../admin/ProductOptions");
s = s + "\\" + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(s);
string path = s;
ole.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + "Extended Properties=" + "\"" + "Excel 12.0;HDR=YES;IMEX=2;READONLY=FALSE;" + "\" ";
OleDbCommand command = new OleDbCommand("select * from[SHEET1$]", ole);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
DataTable dt = (DataTable)ds.Tables[0];
DataTable dt2 = new DataTable("dt2");
Session["dt"] = null;
for (int i = 0; i < dt.Columns.Count; i++)
{
string s2 = dt.Columns[i].ToString();
s2 = s2.Replace("#", ".");
string ProductName = s2.ToString();
if (Session["dt"] == null)
{
DataColumn dCol1 = new DataColumn(ProductName, typeof(System.String));
dt2.Columns.Add(dCol1);
}
}
for (int i = 0; i < dt.Rows.Count; i++)
{
dt2.Rows.Add();
for (int x = 0; x < dt.Columns.Count; x++)
{
dt2.Rows[i][x] = dt.Rows[i][x];
}
}
System.IO.File.Delete(s);
GridView1.DataSource = dt2;
GridView1.DataBind();
GridView1.Visible = true;
string filepath = Server.MapPath("ProductOptions") + "\\" + DDLproduct.SelectedValue + ".xml";
// Session["ss"] = ds;
write_to_xml(dt2,filepath);
}
else
{
Label2.Visible = true;
Label2.Text="[Please Select a file]";
}
Following is the code for write_to_xml() :
public void write_to_xml(DataTable dt, string path)
{
dt.WriteXml(path);
}
Any query or alternative solution would be appreciated... :)
Turn your headers off by HDR=No in your connection string and get your job done.
Before feeding them back to excel with HDR=Yes replace .s with #s using regex or any tool you want in the first row.
Instead of your solution I use Encoding.UTF8 in this way:
using (var fs = new FileStream(xmlFile, FileMode.CreateNew))
{
using (var xw = new XmlTextWriter(fs, Encoding.UTF8))
{
ds.WriteXml(xw);
}
}
And had no problem, this also converts < to < and > to >.

Reading columns from Excel, reformat cells

I am currently trying to read in cells from an excel spread sheet, and it seems to reformat cells when I don't want it to. I want it to come through as plan text. I have read a couple of solutions to this problem and I have implemented them, but I am still having the same issue.
The reader turns dates in numbers and numbers into dates.
Example:
Friday, January 29, 2016 comes out to be : 42398
and
40.00 comes out to be : 2/9/1900 12:00:00 AM
code:
string stringconn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + files[0] + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";
try {
OleDbConnection conn = new OleDbConnection(stringconn);
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [CUAnswers$]", conn);
DataTable dt = new DataTable();
try {
printdt(dt);
I have tried
IMEX=0;
HDR=NO;
TypeGuessRows=1;
This is how I am printing out the sheet
public void printdt(DataTable dt) {
int counter1 = 0;
int counter2 = 0;
string temp = "";
foreach (DataRow dataRow in dt.Rows) {
foreach (var item in dataRow.ItemArray) {
temp += " ["+counter1+"]["+counter2+"]"+ item +", ";
counter2++;
}
counter1++;
logger.Debug(temp);
temp = "";
counter2 = 0;
}
}
I had a similar problem, except it was using Interop to read the Excel spreadsheet. This worked for me:
var value = (range.Cells[rowCnt, columnCnt] as Range).Value2;
string str = value as string;
DateTime dt;
if (DateTime.TryParse((value ?? "").ToString(), out dt))
{
// Use the cell value as a datetime
}
Editted to add new ideas
I was going to suggest saving the spreadsheet as comma-separated values. Then Excel converts the cells to text. It is easy to parse a CSV in C#.
That led me to think of how to programmatically do the conversion, which is covered in Convert xls to csv programmatically. Maybe the code in the accepted answer is what you are looking for:
string ExcelFilename = "c:\\ExcelFile.xls";
DataTable worksheets;
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" + #"Data Source=" + ExcelFilename + ";" + #"Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1""";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
worksheets = connection.GetSchema("Tables");
foreach (DataRow row in worksheets.Rows)
{
// For Sheets: 0=Table_Catalog,1=Table_Schema,2=Table_Name,3=Table_Type
// For Columns: 0=Table_Name, 1=Column_Name, 2=Ordinal_Position
string SheetName = (string)row[2];
OleDbCommand command = new OleDbCommand(#"SELECT * FROM [" + SheetName + "]", connection);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = command;
DataTable dt = new DataTable();
oleAdapter.FillSchema(dt, SchemaType.Source);
oleAdapter.Fill(dt);
for (int r = 0; r < dt.Rows.Count; r++)
{
string type1 = dr[1].GetType().ToString();
string type2 = dr[2].GetType().ToString();
string type3 = dr[3].GetType().ToString();
string type4 = dr[4].GetType().ToString();
string type5 = dr[5].GetType().ToString();
string type6 = dr[6].GetType().ToString();
string type7 = dr[7].GetType().ToString();
}
}
}

Categories