I'm having a excel file in a folder. but i dont know to fetch that file from the folder.
but I'm checking whether the file exists.
here is my code:
protected void Page_Load(object sender, EventArgs e)
{
string filePath = Server.MapPath("~/Upload/Sample.xlsx");
bool fileexists = File.Exists(filePath); //Here fileexists = true
}
I need to save that excel file in sql database.
I need to save the fileName(varchar(256)),Data(varbinary(max)),Path(varchar(256)) of that excel file into sql database.
please help me out
Try this to get and read an xlsx file .
if (Directory.Exists(Server.MapPath("path")))
{
string filename = Path.GetFileName("path");// to get filename
string conStr = string.Empty;
string extension = Path.GetExtension(filename);// get extension
if (extension == ".xls" || extension == ".xlsx")
{
switch (extension)
{
case ".xls": //Excel 1997-2003
conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source='" + mappingPath + "';" + "Extended Properties=Excel 8.0;";
break;
case ".xlsx": //Excel 2007
conStr = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source='" + mappingPath + "';" + "Extended Properties=Excel 8.0;";
break;
default:
break;
}
OleDbConnection connExcel = new OleDbConnection(conStr.ToString());
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
ViewState["SheetName"] = SheetName;
//Selecting Values from the first sheet
//Sheet name must be as Sheet1
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * From [" + SheetName + "]", conStr.ToString()); // to fetch data from excel
da.Fill(dtExcel);
}
This is much simpler than you think, it should be something like:
if (File.Exists(filePath)) {
byte[] data = File.ReadAllBytes(filePath);
string fileName = Path.GetFileName(filePath);
const string query = "INSERT INTO Files (FileName, Data, Path) VALUES (#FileName, #Data, #Path)";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection)) {
command.Parameters.AddWithValue("#FileName", fileName);
command.Parameters.AddWithValue("#Data", data);
command.Parameters.AddWithValue("#Path", filePath);
connection.Open();
command.ExecuteNonQuery();
}
}
Related
I had excel file, button (import), openfiledialog and gridview at VB.Net 2013.
My task is to make a button that will extract all data from excel file to datagridview
openFileDialog1.InitialDirectory = "C:\\Users\\ProgrammerPC1\\Desktop\\DLAV FILES";
openFileDialog1.Title = "Import Master Data";
openFileDialog1.FileName = "";
openFileDialog1.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
try {
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string name = "Sheet1";
string constr = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0; HDR=Yes; IMEX=1;";
System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection(constr);
System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + name + "$]", con);
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
else
{
MessageBox.Show("Operation Cancelled");
}
}catch (Exception err)
{
MessageBox.Show(err.Message);
}
My Error is
external table is not in the expected format
I found that you're using same connection string provider (MS Jet OLEDB 4.0 Provider) for both XLS (for Excel 97-2003) and XLSX (for Excel 2007 & above) files, hence causing external table is not in the expected format error when trying to read XLSX/XLSM files.
You need to use 2 separate connection string and switch them based from file extension stored in OpenFileDialog with Path.GetExtension() method as in given example below:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string extension = Path.GetExtension(openFileDialog1.FileName); // get file extension
string name = "Sheet1"
using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection())
{
switch (extension)
{
case ".xls": // Excel 97-2003 files
// Excel 97-2003 connection string
string xlsconstr = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0; HDR=Yes; IMEX=1;";
con.ConnectionString = xlsconstr;
break;
case ".xlsx": // Excel 2007 files
case ".xlsm":
// Excel 2007+ connection string, see in https://www.connectionstrings.com/ace-oledb-12-0/
string xlsxconstr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 12.0; HDR=Yes; IMEX=1;";
con.ConnectionString = xlsxconstr;
break;
}
using (System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + name + "$]", con))
{
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
}
}
else
{
MessageBox.Show("Operation Cancelled");
}
I made a program to open Excel file.
There are exist data page and blank page.
Can I add only the pages where the data exists in the combo box?
Can I use ButtonEvent to view only pages that contain data?
string filePath = openFileDialog1.FileName;//파일 경로 가져오기
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
//string connectionString = string.Empty;
string sheetName = string.Empty;
using (OleDbConnection con = new OleDbConnection(ConnectStr()))
{
using (OleDbCommand cmd = new OleDbCommand())
{
using (OleDbDataAdapter oda = new OleDbDataAdapter())
{
DataTable dt = new DataTable();
cmd.CommandText = "SELECT * From [" + sheetName + "]";
cmd.Connection = con;
con.Open();
oda.SelectCommand = cmd;
oda.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
}
}
public string ConnectStr()
{
string filePath = openFileDialog1.FileName;
string filename = openFileDialog1.SafeFileName;//파일 이름만 가져오기
string fileExtension = Path.GetExtension(filePath);
string connectionString = string.Empty;
string sheetName = string.Empty;
switch (fileExtension)
{
case ".xls": //Excel 97-03버전
connectionString = string.Format(Excel03ConString, filePath);
break;
case ".xlsx": //Excel 07이상 버전
connectionString = string.Format(Excel16ConString, filePath);
break;
}
return connectionString;
}
I don't really get what is this. But I beg you need to show only specific sheet from spreadsheet correct me if i'm wrong.
There is a SQL commend that we can query from the specific sheet.
try
{
this.txtImportFilePath.Text = opd.FileName;
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" + this.txtImportFilePath.Text + ";Extended Properties=Excel 8.0;");
StringBuilder stbQuery = new StringBuilder();
stbQuery.Append("Select * From [Sheet1$]");
OleDbDataAdapter adp = new OleDbDataAdapter(stbQuery.ToString(), con);
DataSet dsXLS = new DataSet();
adp.Fill(dsXLS);
DataView dvEmp = new DataView(dsXLS.Tables[0]);
trnxlistDataview.DataSource = dvEmp;
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
I'm uploading data to DB table using excel sheet
I'm uploading data to ProductStatisticsTemp table
In that table I have following columns
Product_ID
ProductNameEn
ProductNameAr
this the upload data POST method
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (Request.Files["file"].ContentLength > 0)
{
string fileExtension = System.IO.Path.GetExtension(Request.Files["file"].FileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Server.MapPath("~/Content/ExcelFiles/") + Request.Files["file"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["file"].SaveAs(fileLocation);
string excelConnectionString = string.Empty;
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
//connection String for xls file format.
if (fileExtension == ".xls")
{
excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
//connection String for xlsx file format.
else if (fileExtension == ".xlsx")
{
excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
//Create Connection to Excel work book and add oledb namespace
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
DataTable dt = new DataTable();
dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
String[] excelSheets = new String[dt.Rows.Count];
int t = 0;
//excel data saves in temp file here.
foreach (DataRow row in dt.Rows)
{
excelSheets[t] = row["TABLE_NAME"].ToString();
t++;
}
OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
string query = string.Format("Select * from [{0}]", excelSheets[0]);
using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
{
dataAdapter.Fill(ds);
}
}
if (fileExtension.ToString().ToLower().Equals(".xml"))
{
string fileLocation = Server.MapPath("~/Content/ExcelFiles") + Request.Files["FileUpload"].FileName;
if (System.IO.File.Exists(fileLocation))
{
System.IO.File.Delete(fileLocation);
}
Request.Files["FileUpload"].SaveAs(fileLocation);
XmlTextReader xmlreader = new XmlTextReader(fileLocation);
// DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
string conn = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
SqlConnection con = new SqlConnection(conn);
string query = "Insert into ProductStatisticsTemp(Product_ID,ProductNameEn,ProductNameAr) Values('" + ds.Tables[0].Rows[i][0] + "','" + ds.Tables[0].Rows[i][1] + "','" + ds.Tables[0].Rows[i][2] )";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
return RedirectToAction("FileUpload", "FileUpload");
}
But in here data saving smoothly , but ProductNameAr fields Arabic letters values save as "?"
ex: If excel value حساب التوفير للاستثمار Albrka
then its saving in database table as ???? ??????? ????????? Albrka
How to save as exact format in the excel sheet
ps. this ProductNameAr data type in Database table is NVARCHAR
You use non-Unicode string literals 'value' when you should use Unicode literals in the form N'value'
You better rewrite as parameterized SqlCommand passing the values using AddWithValue
string query = "Insert into ProductStatisticsTemp(Product_ID,ProductNameEn,ProductNameAr) Values(#Product_ID,#ProductNameEn,#ProductNameAr)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#Product_ID", ds.Tables[0].Rows[i][0]);
...etc...
You don't need to re-create and open the SqlConnection inside the loop
i created web application using c# to import excel file into Microsoft Dynamics CRM. I used Fileupload to import the excel file.
Here is the code snippet:
Import Button:
if (FileUpload1.PostedFile != null)
{
string FilePath = Path.GetFileName(this.FileUpload1.FileName);
string FileName = Server.MapPath(Path.GetFileName(FilePath));
string Extension = Path.GetExtension(this.FileUpload1.FileName);
DataTable dt = ImportData(FileName, Extension);
And this is the ImportData code:
private DataTable ImportData(string Filepath, string Extension)
{
string connString = "";
DataTable dt = new DataTable();
switch (Extension)
{
case ".xls":
connString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
break;
case ".xlsx":
connString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
break;
}
connString = string.Format(connString, Filepath, 1);
try
{
OleDbConnection excelConn = new OleDbConnection(connString);
OleDbCommand excelCmd = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
excelCmd.Connection = excelConn;
excelConn.Open();
DataTable dtexcelschema;
dtexcelschema = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string SheetName = dtexcelschema.Rows[0]["TABLE_NAME"].ToString(); **The Error Come from this line**
excelConn.Close();
excelConn.Open();
excelCmd.CommandText = "Select * from [" + SheetName + "]";
oda.SelectCommand = excelCmd;
oda.Fill(dt);
excelConn.Close();
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
return dt;
}
When i tried to import excel to CRM. I got this message : "There is no row at position 0."
I dont know what happen here. Actually before i create web application, i created windows application using this code, and succes to import data. But when i copy this code into web application, i got that message.
EDITED
This is connection string inside web config:
<add name ="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
<add name ="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR={1}'"/>
Use This:
string Filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
string Folderpath = ConfigurationManager.AppSettings["FolderPath"];
string Filepath = Server.MapPath(Folderpath + Filename);
FileUpload1.SaveAs(Filepath);
DataTable dt = ImportData(Filepath, Extension);
I have a gridview with 1000 rows and I also have an export & import functionality. For ex. when I export 100 rows and do changes to them, and import them again, then only those 100 rows changed will be reflected. The remaining changed rows remain the same.
I am using this code below to import data to the database. Now how can I add new rows while importing on top of this working model.
Really appreciate any guidance.
CODE:
protected void btnImportXL_Click(object sender, EventArgs e)
{
string strSqlTable = "##TempupdatePm";
string sexcelconnectionstring = "";
string strFileType = Path.GetExtension(FileUploadExcel.FileName).ToLower();
// string path = FileUploadExcel.PostedFile.FileName;
string query = "";
string FileName = string.Empty;
//GridView2.Visible = false;
FileName = Path.GetFileName(FileUploadExcel.PostedFile.FileName);
string Extension = Path.GetExtension(FileUploadExcel.PostedFile.FileName);
string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
// string path = FileName;
//Get file name of selected file
string path = Path.GetFileName(Server.MapPath(FileUploadExcel.FileName));
System.IO.File.Delete(Server.MapPath(FolderPath) + path);
//Save selected file into server location
FileUploadExcel.SaveAs(Server.MapPath(FolderPath) + path);
//Get file path
string filePath = Server.MapPath(FolderPath) + path;
if (strFileType != String.Empty)
{
//Connection String to Excel Workbook
if (strFileType.Trim() == ".xls")
{
sexcelconnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
}
else if (strFileType.Trim() == ".xlsx")
{
sexcelconnectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please upload the correct file format')", true);
return;
}
try
{
OleDbConnection conn = new OleDbConnection(sexcelconnectionstring);
if (conn.State == ConnectionState.Closed)
conn.Open();
System.Data.DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname = dt.Rows[0]["Table_Name"].ToString();
query = "SELECT * FROM [" + sheetname + "]";
OleDbCommand cmd = new OleDbCommand(query, conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
oledbconn.Open();
OleDbCommand oledbcmd = new OleDbCommand(query, oledbconn);
OleDbDataReader dReader;
dReader = oledbcmd.ExecuteReader();
string create1 = "Create Table " + strSqlTable + "( [CODE] [varchar](10) NOT NULL,[Name] [varchar](150) NOT NULL,[Group] [varchar](10) NOT NULL, [Team] [varchar](10) NOT NULL, [Size1] [varchar](10) NOT NULL, [Size2] [varchar](10) NOT NULL";
SqlConnection sqlconn2 = new SqlConnection(strConnectionString);
SqlCommand sqlcmd2 = new SqlCommand(create1, sqlconn2);
sqlconn2.Open();
sqlcmd2.ExecuteNonQuery();
SqlBulkCopy sqlBulk = new SqlBulkCopy(sqlconn2);
sqlBulk.DestinationTableName = strSqlTable;
sqlBulk.WriteToServer(dReader);
string update1 = "update o set o.Size1=t.Size1,O.Size2=t.Size2 from Application as o inner join ##TempupdatePm as t on(o.CODE=t.CODE )and (o.Team=t.Team) and (o.Group=t.Group) where (o.CODE=t.CODE ) and (o.Group=t.Group)";
SqlCommand sqlcmd1 = new SqlCommand(update1, sqlconn2);
sqlcmd1.ExecuteNonQuery();
string drop1 = "drop Table " + strSqlTable;
SqlCommand sqlcmd3 = new SqlCommand(drop1, sqlconn2);
sqlcmd3.ExecuteNonQuery();
oledbconn.Close();
conn.Close();
conn.Dispose();
sqlconn2.Close();
ClientScript.RegisterStartupScript(Page.GetType(), "alert", "alert('Data saved successfully');window.location='ApplicationInfo.aspx';", true);
}
catch (Exception ex)
{
}
//objDA.BindGrid(GridView1, "select * from " + strSqlTable);
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Please select a file to import the data.')", true);
}
}
Do something like this with your sql query to insert and update with one query.
INSERT INTO MyTable (field1, field2, fieldN)
VALUES ("value1","value2", "valueN")
ON DUPLICATE KEY UPDATE
field1=VALUES(value1)
field2=VALUES(value2)
fieldN=VALUES(valueN)
//and so on.
you can just write a insert statement before update something like
Insert in to table select CODE,Size1,Size2 from #temp_table where CODE not in (Select code from table )
Then proceed as before.