How to upload multiple Excel files in asp.net - c#

This is the 1st table called excel2 for storing English characters
This is the 2nd table called excel3 for storing numbers
For the Excel file, there's two sheet in total, the first sheet store data of English characters and the second sheet store data of numbers.
User can choose to import multiple Excel files at the same time.
Now, when user select 3 excel file, the foreach loop is looping 3 times, but the data being inserted to the database only contain data from the 1st excel file repeatedly.
Any idea? Many thanks
public partial class multipleexcelimport : System.Web.UI.Page
{
protected void importfile()
{
String MyConString = "SERVER=localhost;" + "DATABASE=mysql_testing;" + "UID=root;" + "PASSWORD=tammy;SslMode=none";
if (this.uploadfile.HasFile)
{
string[] segments = fn.Split('.');
string fileExt = segments[segments.Length - 1];
if (fileExt != "xlsx")
{
showMessage("輸入錯誤", "請上傳正確檔案xlsx");
return;
}
foreach (var file in uploadfile.PostedFiles)
{
var fn = file.FileName;
string newfileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + fn;
string filepath = Server.MapPath(ConfigurationSettings.AppSettings["UPLOAD_FOLDER"]) + newfileName;
this.uploadfile.SaveAs(filepath);
ExcelPackage xlWorkbook = new ExcelPackage(new FileInfo(filepath));
ExcelWorksheet xlRange = xlWorkbook.Workbook.Worksheets[1];
int rowCount = xlRange.Dimension.End.Row;
ExcelWorksheet xlRange2 = xlWorkbook.Workbook.Worksheets[2];
int rowCount2 = xlRange2.Dimension.End.Row;
string sql = "";
string linkid = "";
MySqlConnection conn = null;
MySqlDataAdapter msda = null;
DataSet ds = null;
List<string> FailList = new List<string>();
conn = new MySqlConnection(MyConString);
DateTime dTime = DateTime.Now;
string now_time = dTime.ToString("yyyy-MM-dd HH:mm:ss");
conn.Open();
conn.Close();
using (TransactionScope scope = new TransactionScope())
{
try
{
conn.Open();
//sheet1
for (int i = 2; i <= rowCount; i++)
{
string dates = xlRange.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel2 set"
+ " excel = ?dates;"
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("dates", dates);
}
//sheet2
for (int i = 2; i <= rowCount2; i++)
{
string excel3 = xlRange2.Cells[i, 1].Value.ToString();
sql = "INSERT INTO mysql_testing.excel3 set"
+ " excel3 = ?excel3;" ;
ds = new DataSet();
msda = new MySqlDataAdapter(sql, conn);
msda.SelectCommand.Parameters.AddWithValue("excel3", excel3);
}
showMessage("alert", "success");
scope.Complete();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
else
{
showMessage("error", "select file plz");
ScriptManager.RegisterStartupScript(this, this.GetType(), "tab", "$('.nav-tabs a[href=\"#massimport\"]').tab('show')", true);
}
}
public void showMessage(string title, string content)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + content + "');", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
importfile();
}
}

Related

The Microsoft Office Access database engine could not find the object 'Sheet1$'. in asp.net c# while uploading xlsx file

I have an excel file which I am trying to upload but its getting failed with error as below
The Microsoft Office Access database engine could not find the object 'Sheet1$'.
The error is causing at this line in the below code
da.Fill(dt);
And full code is below
private void UploadDataForAnyVendor(string strUser)
{
try
{
if (fluUploadBtn.HasFile)
{
string ConStr = "";
string ext = Path.GetExtension(fluUploadBtn.FileName).ToLower();
if (ext == ".xls" || ext == ".xlsx")
{
string path = Server.MapPath("~/UploadIPFEEData/");
//string strFolderName = "INDUS\\";
string strAnyFolder = "ANYFOLDER\\";
string strDeleteFile = Server.MapPath("~/ANYFOLDER/") + Path.GetFileName(fluUploadBtn.PostedFile.FileName);
string newPath = Path.Combine(path, strAnyFolder.ToString());
DirectoryInfo objDirectory = new DirectoryInfo(newPath);
string day = DateTime.Now.ToString("ss_mm_hh_dd_MM_yyyy");
if (!objDirectory.Exists)
{
System.IO.Directory.CreateDirectory(newPath);
newPath = newPath + fluUploadBtn.FileName;
}
newPath = newPath + fluUploadBtn.FileName;
if ((System.IO.File.Exists(fluUploadBtn.FileName)))
{
System.IO.File.Delete(fluUploadBtn.FileName);
}
if (ext.Trim() == ".xls")
{
ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + newPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (ext.Trim() == ".xlsx")
{
ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + newPath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection mycon = new OleDbConnection(ConStr);
if (mycon.State == ConnectionState.Closed)
{
mycon.Open();
}
OleDbCommand cmd = new OleDbCommand("Select * from [Sheet1$]", mycon);
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = cmd;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
da.Fill(dt);
//loadfile(newPath, ext);
string strAssignedStates = string.Empty;
strAssignedStates = Convert.ToString(ViewState["States"]);
string strOne = strStates;
string[] strStateArray = new string[] { "" };
strStateArray = strOne.Split(',');
string errMsg = string.Empty;
int j = 1; string key = "StateNotFoundAlert" + j.ToString();
for (int i = 0; i < strStateArray.Length; i++)
{
if (dt.Rows[0]["CIRCLE"].ToString() == strStateArray[i].Trim().ToString())
{
if (dt.Rows.Count > 0)
{
errMsg = "1";
dt.TableName = "RecodSet";
string xml = ConvertDatatableToXML(dt);
mycon.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('File uploaded successfully.!!');", true);
}
else
{
string noData = "No data to upload.";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "script", noData, false);
}
}
else
{
errMsg = "0";
}
}
if (errMsg == "0" && errMsg != "1")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('User is not authorised to upload data for state mentioned in excel report ');", true);
}
}
else
{
string key = "Invalid vendor";
ScriptManager.RegisterStartupScript(this, this.GetType(), key, "alert('Invalid file extension !!!');", true);
}
}
}
catch (Exception)
{
throw;
}
}
Please suggest where I am going wrong

No value given for one or more required parameters error - Excel

I am getting data from excel and showing it in DataGridWiew.
I have two textboxes, one is for starting index for first record and other is for last record.
Code works fine. But lets suppose starting record is 1 and ending is 10 when I change 10 to 1 or 2 it gives me an error in this line:
adapter.Fill(dataTable);
Full Code is below:
public DataSet Parse(string fileName)
{
string connectionString = string.Format("provider = Microsoft.Jet.OLEDB.4.0; data source = {0}; Extended Properties = Excel 8.0;", fileName);
DataSet data = new DataSet();
foreach (var sheetName in GetExcelSheetNames(connectionString))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string query = "";
var dataTable = new DataTable();
if(tbStarting.Text.Trim()=="" && tbEnding.Text.Trim() == "")
{
query = string.Format("SELECT * FROM [{0}]", sheetName);
}
else
{
query = string.Format("SELECT * FROM [{0}] where SrNo between " + int.Parse(tbStarting.Text.Trim()) + " and " + int.Parse(tbEnding.Text.Trim()) + " order by SrNo", sheetName);
}
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
con.Close();
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
OleDbConnection con = null;
DataTable dt = null;
con = new OleDbConnection(connectionString);
con.Open();
dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheetNames = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheetNames[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheetNames;
}
Why this is happening please help me?
Looking at the code, it seems that your procedure is working when you ask to retrieve all the record in each table. But you are not showing which table (Sheet) is actually used afterwars.
Chances are, you are using the first one only.
When you submit some parameters, only one of the tables (Sheets) can fulfill those requirements. The other(s) don't, possibly because a field named [SrNo] is not present.
This causes the More Parameters Required error when trying to apply a filter.
Not related to the error, but worth noting: you don't need to recreate the whole DataSet + DataTables to filter your DataSources.
The DataSet.Tables[N].DefaultView.RowFilter can be used to get the same result without destroying all the objects each time a filter is required.
RowFilter has some limitations in the language (e.g. does not support BETWEEN, Field >= Value1 AND Field <= Value2 must be used), but it's quite effective.
This is a possible setup:
(xDataSet is a placeholder for your actual DataSet)
//Collect the values in the TextBoxes in a string array
private void button1_Click(object sender, EventArgs e)
{
string[] Ranges = new string[] { tbStarting.Text.Trim(), tbEnding.Text.Trim() };
if (xDataSet != null)
FilterDataset(Ranges);
}
private void FilterDataset(string[] Ranges)
{
if (string.IsNullOrEmpty(Ranges[0]) & string.IsNullOrEmpty(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = null;
else if (string.IsNullOrEmpty(Ranges[0]) | string.IsNullOrEmpty(Ranges[1]))
return;
else if (int.Parse(Ranges[0]) < int.Parse(Ranges[1]))
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo >= {0} AND SrNo <= {1}", Ranges[0], Ranges[1]);
else
xDataSet.Tables[0].DefaultView.RowFilter = string.Format("SrNo = {0}", Ranges[0]);
this.dataGridView1.Update();
}
I've modified your code you code a bit to handle those requirements.
(I've left here those filters anyway; they're not used, but if you still want them, they are in a working condition)
DataSet xDataSet = new DataSet();
string WorkBookPath = #"[Excel WorkBook Path]";
//Query one Sheet only. More can be added if necessary
string[] WBSheetsNames = new string[] { "Sheet1" };
//Open the Excel document and assign the DataSource to a dataGridView
xDataSet = Parse(WorkBookPath, WBSheetsNames, null);
dataGridView1.DataSource = xDataSet.Tables[0];
dataGridView1.Refresh();
public DataSet Parse(string fileName, string[] WorkSheets, string[] ranges)
{
if (!File.Exists(fileName)) return null;
string connectionString = string.Format("provider = Microsoft.ACE.OLEDB.12.0; " +
"data source = {0}; " +
"Extended Properties = \"Excel 12.0;HDR=YES\"",
fileName);
DataSet data = new DataSet();
string query = string.Empty;
foreach (string sheetName in GetExcelSheetNames(connectionString))
{
foreach (string WorkSheet in WorkSheets)
if (sheetName == (WorkSheet + "$"))
{
using (OleDbConnection con = new OleDbConnection(connectionString))
{
DataTable dataTable = new DataTable();
if ((ranges == null) ||
(string.IsNullOrEmpty(ranges[0]) || string.IsNullOrEmpty(ranges[1])) ||
(int.Parse(ranges[0]) > int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}]", sheetName);
else if ((int.Parse(ranges[0]) == int.Parse(ranges[1])))
query = string.Format("SELECT * FROM [{0}] WHERE SrNo = {1}", sheetName, ranges[0]);
else
query = string.Format("SELECT * FROM [{0}] WHERE (SrNo BETWEEN {1} AND {2}) " +
"ORDER BY SrNo", sheetName, ranges[0], ranges[1]);
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(query, con);
adapter.Fill(dataTable);
data.Tables.Add(dataTable);
};
}
}
return data;
}
static string[] GetExcelSheetNames(string connectionString)
{
string[] excelSheetNames = null;
using (OleDbConnection con = new OleDbConnection(connectionString))
{
con.Open();
using (DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null))
{
if (dt != null)
{
excelSheetNames = new string[dt.Rows.Count];
for (int i = 0; i < dt.Rows.Count; i++)
{
excelSheetNames[i] = dt.Rows[i]["TABLE_NAME"].ToString();
}
}
}
}
return excelSheetNames;
}

Excel Import Error in ASP.net

I am trying to import an excel to database from asp.net website through dataset.
Here is my first part.
int xlColCount = 1;
wb = app.Workbooks.Open(FilePath, 0, false, 5, "", "", true, Ex.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
ws = (Ex.Worksheet)wb.ActiveSheet;
xlColCount = ws.Columns.Count;
xlColCount = ws.UsedRange.Columns.Count;
ws.Columns.ClearFormats();
xlColCount = ws.UsedRange.Columns.Count;
//creating datacolumns
for (int i = 0; i < xlColCount; i++)
{
try
{
DSname.Tables[0].Columns.Add(((Ex.Range)ws.Cells[1,strColArr[i]]).Value2.ToString().Trim());
}
catch(Exception ex)
{
//error occured
}
}
First I am creating the column name based on the excel heading into dataset column. here xlColCount=198 (total no.of columns from the excel template and all are filled ) but when reaching 172th column (i=172) it is giving index out of range error.
What could be the reason? I need to create a dataset with column names from all excel column names.
Check your strColArr[i] array capacity..may be initialized with 172 or less in size.
May be you will have better results (and performance) with ADO.NET and System.Data.OleDb :
string filePath = #"C:\Workbook1.xls";
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0\";";
OleDbConnection connection = new OleDbConnection(connectionString);
string cmdText = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(cmdText, connection);
command.Connection.Open();
OleDbDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}\t{1}", reader[0].ToString(), reader[1].ToString());
}
}
string filePath = "":
OleDbCommand cmd = new OleDbCommand(); ;
OleDbDataAdapter oleda = new OleDbDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
UserBase loginUser = (UserBase)Session["LoggedUser"];
SearchFilter filter = new SearchFilter();
string action = "ExportDocumentType";
filter.DocumentTypeID = Convert.ToInt32(cmbDocumentType.SelectedValue);
filter.DepartmentID = Convert.ToInt32(cmbDepartment.SelectedValue);
try
{
Logger.Trace("Started Extracting Soft Data", Session["LoggedUserId"].ToString());
// need to pass relative path after deploying on server
oledbConn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
filePath + ";Extended Properties='Excel 12.0;';");
try
{
oledbConn.Open();
}
catch
{
string con = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.0;HDR=Yes;IMEX=1";
oledbConn = new OleDbConnection(con);
oledbConn.Open();
}
// Get the data table containg the schema guid.
dt = oledbConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
throw new Exception(" No sheets available!");
}
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
// Add the sheet name to the string array.
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
// Get column names of selected document type
string SelectCommand = getIndexFieldsList();
SelectCommand = "SELECT " + SelectCommand + " FROM [" + excelSheets[0] + "]";
cmd.CommandText = SelectCommand;
oleda = new OleDbDataAdapter(cmd);
try
{
oleda.Fill(ds);
}
catch
{
throw new Exception("Selected file is not matching to " + cmbDocumentType.SelectedItem.Text + ".");//Bug Wrtier DMS ENHSMT 1-1012 M
}
string strXml = string.Empty;
if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
// note: Do ur code here.. i prefer to create a insert satement from here using looping it out
}
else
{
throw new Exception(" No data available in uploaded file!");//Bug Wrtier DMS ENHSMT 1-1012 M
}
}
catch (Exception ex)
{
Logger.Trace("Exception:" + ex.Message, Session["LoggedUserId"].ToString());
throw new Exception(ex.Message.ToString());
}
finally
{
// Clean up.
if (oledbConn != null)
{
oledbConn.Close();
oledbConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
if (ds != null)
{
ds.Dispose();
}
}
}

how to delete first field and all values of this field in .CSV file using C#

I want to load .csv file and then import to SQl database. But before I do that, I want to do something to delete first field (in header) and also all values of this field.
this below is the example of my .csv file :
> TableId|PERIODE|DATEBALANCEASOF|ACCCODE|CUSTNAME|CUSTGROUP|
> TB_001|201501|2015-01-01|11-0001|DYNAMIC EXPRESS|11|
> TB_001|201501|2015-01-01|11-0002|DYNAMIC EXPRESS|12|
> TB_001|201501|2015-01-01|11-0003|DYNAMIC EXPRESS|13|
> TB_001|201501|2015-01-01|11-0004|DYNAMIC EXPRESS|14|
before I import that .csv file, I need my .csv file willbe like this below :
PERIODE|DATEBALANCEASOF|ACCCODE|CUSTNAME|CUSTGROUP|
201501|2015-01-01|11-0001|DYNAMIC EXPRESS|11|
201501|2015-01-01|11-0002|DYNAMIC EXPRESS|12|
201501|2015-01-01|11-0003|DYNAMIC EXPRESS|13|
201501|2015-01-01|11-0004|DYNAMIC EXPRESS|14|
this below is my code :
public void readCSVManual(string pathLocalSuccess, string pathHistory, string modul)
{
try
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"server=" + serverDB + "; database=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
string[] files = Directory.GetFiles(pathLocalSuccess);
if (files == null)
{
MessageBox.Show("Files not found");
}
foreach (string file in files)
{
FileInfo fileInf = new FileInfo(file);
string filename = fileInf.Name;
StreamReader reader = new StreamReader(file);
string line = reader.ReadLine();
string[] value = line.Split('|');
var list = new List<string>(value);
list.RemoveAt(0);
value = list.ToArray();
//string[] v = string(nValue.ToArray());
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!reader.EndOfStream)
{
value = reader.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "ACC_004";
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
con.Close();
reader.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Please help me to resolve this problem..
Thanks for everyone who respons my question,
Actually I already solve this problem using a little editing in my code
this below is my code and works for me :
public void readCSVAutomatic(string pathLocalSuccess, string pathHistory, string pathLogFolderSuccess, string pathErrorLog, string modul)
{
try
{
string[] files = Directory.GetFiles(pathLocalSuccess);
foreach (string file in files)
{
FileInfo fileInf = new FileInfo(file);
string filename = fileInf.Name;
StreamReader reader = new StreamReader(file);
string line = reader.ReadLine();
string[] value = line.Split('|');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!reader.EndOfStream)
{
//value = value.
value = reader.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
string xTableName = dt.Rows[0].ItemArray[0].ToString();
string xPeriode = dt.Rows[0].ItemArray[1].ToString();
dt.Columns.RemoveAt(0);
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=" + serverDB + "; Initial Catalog=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
con.Open();
SqlCommand com = con.CreateCommand();
string strDelete = "DELETE FROM " + xTableName + " WHERE PERIODE='" + xPeriode + "'";
com.CommandText = strDelete;
com.Connection = con;
com.ExecuteNonQuery();
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = xTableName;
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
con.Close();
reader.Close();
moveFileAfterImported(pathLocalSuccess, filename, pathHistory);
createLogCSVSuccessImported(pathLogFolderSuccess, "File Imported","Message");
}
}
catch(Exception ex)
{
createErrorLogImportCSV(pathErrorLog, "ErrorImportCSV", ex.ToString());
}
}
This seems to do the job for me:
First start by reading in all the files:
var datatables =
Directory
.GetFiles(pathLocalSuccess)
.Select(file => File.ReadAllLines(file).Select(x => x.Split('|')).ToArray())
.Select(lines => new
{
headers = lines[0].Skip(1).ToArray(),
lines = lines.Skip(1).Select(l => l.Skip(1).ToArray()).ToArray(),
})
.Select(x =>
{
var dt = new DataTable();
foreach (var dc in x.headers)
{
dt.Columns.Add(new DataColumn(dc));
}
foreach (var line in x.lines.Skip(1).Where(y => y.Length == x.headers.Length))
{
var row = dt.NewRow();
row.ItemArray = line;
dt.Rows.Add(row);
}
return dt;
})
.ToArray();
Then it's a simple matter of loading all the data. This code only opens the connection once. It should be quite fast.
if (!datatables.Any())
{
MessageBox.Show("Files not found");
}
else
{
using (var con = new SqlConnection())
{
con.ConnectionString = #"server=" + serverDB + "; database=" + DB + "; Trusted_Connection=" + trustedConnection + "; user=" + UserDB + "; password=" + PassDB + "";
foreach (var dt in datatables)
{
var bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "ACC_004";
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
}
con.Close();
}
}
The important part for skipping the first field is found in this code:
.Select(lines => new
{
headers = lines[0].Skip(1).ToArray(),
lines = lines.Skip(1).Select(l => l.Skip(1).ToArray()).ToArray(),
})

Convert date format on fly in asp.net c#

i am uploading an excel file which has a date column having this format "dd-mm-yyyy". I am trying to convert it on fly into this format mm/dd/yyyy.
string[] dsplit = row[6].ToString().Split('-');
obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();
but it throws error, some hidden error.
Here is the whole code. I have tried a alot and nothing works expectedly
protected void SaveEmployeefrom_Click(object sender, EventArgs e)
{
uploadExcelfile();
}
public List<ClsEmployee> uploadExcelfile()
{
List<ClsEmployee> list = new List<ClsEmployee>();
DataTable tb = new DataTable();
try
{
if (employeeregistration.HasFile)
{
string name = DateTime.Now.ToString("hhmmss_ddmmyy");
name = name + employeeregistration.FileName;
employeeregistration.SaveAs(Server.MapPath("~/ExcelFiles/") + name);
string path = System.IO.Path.GetFullPath(Server.MapPath("~/ExcelFiles/") + name);
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
if (Path.GetExtension(path) == ".xls")
{
excelconnection = new OleDbConnection(connString);
excelconnection.Open();
}
else if (Path.GetExtension(path) == ".xlsx")
{
excelconnection = new OleDbConnection(connString);
excelconnection.Open();
}
OleDbCommand cmd = new OleDbCommand("SELECT [Name],[ID],[Mobile No],[Phone],[Emirates],[Nationality],[ExpiryDate],[Address] FROM [sheet1$]", excelconnection);
OleDbDataAdapter oleda = new OleDbDataAdapter(cmd);
oleda.Fill(tb);
foreach (DataRow row in tb.Rows)
{
if (!string.IsNullOrEmpty(row[6].ToString()))
{
ClsEmployee obj = new ClsEmployee();
obj.ID = 0;
// obj.Employer_ID=row[0].ToInt32();
obj.EmployeeName = row[0].ToString();
obj.EmployeeUniqueID = row[1].ToString();
obj.MobileNumber = row[2].ToString();
obj.PhoneNumber = row[3].ToString();
obj.Emirates = row[4].ToString();
obj.Nationality = row[5].ToString();
//from excel its dd-mm-yyyy
string[] dsplit = row[6].ToString().Split('-');
obj.ExpiryDate = string.Format("{0}/{1}/{2}", dsplit[1], dsplit[0], dsplit[2]).ToDate();
// obj.ExpiryDate = row[6].ToDate(); //mm-dd-yyyy
obj.Address = row[7].ToString();
list.Add(obj);
}
}
excelconnection.Dispose();
if (File.Exists(path))
{
File.Delete(path);
}
int total = tb.Rows.Count;
if (total>0)
{
GV_Employee.DataSource = null;
GV_Employee.DataSource = list;
GV_Employee.DataBind();
GV_Employee.Visible = true;
ResultLabel.ResultLabelAttributes("Uploaded successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
ResultPanel.Controls.Add(ResultLabel);
}
else
{
ResultLabel.ResultLabelAttributes("No Record In Excel Sheet !!!", ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
//txtSerialQuantity.Text = total.ToString();
////// trbtnCheckAll.Visible = true;
////div_automatic.Visible = true;
////lbl_totalSelected.Text = "Total Selected = " + total.ToString();
}
}
catch (Exception x)
{
x.ToString(); //ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultLabel.ResultLabelAttributes(x.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
return list;
}
protected void Button1_Click(object sender, EventArgs e)
{
ClsEmployee obj1 = new ClsEmployee();
List<ClsEmployee> list = new List<ClsEmployee>();
try
{
foreach (GridViewRow item in GV_Employee.Rows)
{
ClsEmployee obj = new ClsEmployee();
obj.ID = 0;
obj.Employer_ID = cmbEmployer.SelectedValue.ToInt32();// ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_EmployerID")).Text.ToInt32();
obj.EmployeeName = ((Literal)item.FindControl("Ltrl_Name")).Text.ToString();
obj.EmployeeUniqueID = ((Literal)item.FindControl("Ltrl_EmployeeUniqueID")).Text.ToString();
obj.MobileNumber = ((Literal)item.FindControl("Ltrl_Mobile")).Text.ToString();
obj.PhoneNumber = ((Literal)item.FindControl("Ltrl_PhoneNo")).Text.ToString();
obj.Emirates_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Emirates")).Text.ToInt32();
obj.Nationality_ID = ((Literal)GV_Employee.Rows[1].FindControl("Ltrl_Nationality")).Text.ToInt32();
obj.ExpiryDate = ((Literal)item.FindControl("Ltrl_Expiry")).Text.ToDate();
obj.Address = ((Literal)item.FindControl("Ltrl_Address")).Text.ToString();
obj.LFMD = "";
obj.RFMD = "";
obj.PinCode = "";
obj.IsFingerAuth = false;
obj.IsActive = true;
list.Add(obj);
}
obj1.SaveEmployeefromExcelFile(list);
ResultLabel.ResultLabelAttributes("Save successfull !!!", ProjectUserControls.Enums.ResultLabel_Color.Yellow);
ResultPanel.Controls.Add(ResultLabel);
GV_Employee.DataSource = null;
GV_Employee.Visible = false;
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.ToString(), ProjectUserControls.Enums.ResultLabel_Color.Red);
ResultPanel.Controls.Add(ResultLabel);
}
}
Try this code.
DateTime dt = DateTime.Parse(row[6].toString());
string date = dt.ToString("dd/MM/yyyy");
I assume row[6] is a DateTime when you get from excel, you just need;
row[6].ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
Convert a DateTime to string and splitting it a generally bad idea. mm specifier is for minutes, MM is for months by the way.
Try This..
String MyString = "12-30-2014"; // get value from text field
DateTime MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "MM-dd-yyyy",null);
String MyString_new = MyDateTime.ToString("dd-MM-yyyy");

Categories

Resources