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");
}
Related
I wanna read data from excel spreadsheet and insert them into Access data base(.accdb). there is a problem with data format in excel. some cells are in incorrect type. Correct format for example is 99999 and incorrect is 9999-888 . because of dash(-) ole data adapter return null values instead of text. how should i get whole cell block?
I have tried change the cell format of excel from General to Text but the problem is still available.
thanks
string connectionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=Excel 12.0;";
using (OleDbConnection connectionExcel = new OleDbConnection(connectionStringExcel))
{
OleDbDataAdapter daExcel = new OleDbDataAdapter(#"SELECT * FROM [priclist$]", connectionExcel);
DataTable dtExcel = new DataTable();
daExcel.Fill(dtExcel);
dataGridView1.DataSource = dtExcel;
}
By default, the Microsoft.ACE.OLEDB.12.0 provider tries to determine variable type for each column, and assumes the majority type is the column type.
You can override this behaviour by specifying IMEX=1 in the connection string, which uses text when encountering mixed-field types instead of setting the ones not matching the type to Null. Then you can handle the values in your C# code:
string connectionStringExcel = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties=Excel 12.0;IMEX=1;";
Read more about the IMEX property by following the link in the comment below
I use the following code to transfer data from Excel to datagrid :
private void btnreadExcell_MouseDown(object sender, MouseButtonEventArgs e)
{
try
{
string filePath = string.Empty;
string fileExt = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
Nullable<bool> result = ofd.ShowDialog();
if (result == true)//if there is a file choosen by the user
{
filePath = ofd.FileName;//get the path of the file
try
{
DataTable dtExcel = new DataTable();
dtExcel = ReadExcel(filePath, fileExt);//read excel file
// dataGrid.Visible = true;
dataGrid.ItemsSource = dtExcel.DefaultView;
datagridheader();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
con.Close();
}
catch { MessageBox.Show("error");}
}
public DataTable ReadExcel(string fileName, string fileExt)
{
DataTable dtexcel = new DataTable();
try
{
string conn = string.Empty;
if (fileExt.CompareTo(".xls") == 0)//compare the extension of the file
conn = #"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties='Excel 8.0;HRD=Yes;IMEX=1';";//for below excel 2007
else
conn = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1';";//for above excel 2007
using (OleDbConnection con = new OleDbConnection(conn))
{
try
{
OleDbDataAdapter oleAdpt = new OleDbDataAdapter("select * from [Sheet1$]", con);//here we read data from sheet1
oleAdpt.Fill(dtexcel);//fill excel data into dataTable
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
conn.Clone();
}
catch { MessageBox.Show("error"); }
return dtexcel;
}
My error has been Solved!!! with set both IMEX=1 And HDR=No. if you have changed your header in excel files(first row) use below code to solve same problem as i asked above.
try this
(two connection string have same meaning)
string connectionStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + ";Extended Properties='Excel 12.0;HDR=No;IMEX=1';"
Or
string connectionStringExcel = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +"T13970524.xlsx" + ";Extended Properties=\"Excel 12.0 Xml;HDR=No;IMEX=1\";";
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 am generating excel file with JS,then uploading it in a temporary folder then reading it after uploading.Its giving me error " External table is not in the expected format." when I am trying to read the generated Excel file(its in xls fomat,same as with xlsx), If I make excel file in MS Excel and read it,its working fine
This is how I am generating
function GenerateExcel() {
var tab_text = $("#hdnUserData").val();
tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text = tab_text.replace(/<img[^>]*>/gi, ""); // remove if u want images in your table
tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
txtArea1.document.open("txt/html", "replace");
txtArea1.document.write(tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"Users Report.xls");
//sa = txtArea1.document.execCommand('SaveAs', true, 'Error Report.xsl');
}
else//other browser not tested on IE 11
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
return (sa);
}
the excel data in columns like this
UserID Name Username
and hidden field have data in CSV like this
1,Test,test123;2,myuser,muser1
This is how I am reading excel
using (var conn = new OleDbConnection())
{
var dt = new DataTable("dtExcel");
string importFileName = path;//Path of uploaded excel file with filename
string fileExtension = System.IO.Path.GetExtension(importFileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + importFileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'";
conn.Open();
DataTable dtSheets = conn.GetSchema("Tables");
string firstSheet = dtSheets.Rows[0]["TABLE_NAME"].ToString();
using (var comm = new OleDbCommand())
{
comm.CommandText = "select * from [" + firstSheet + "]";
comm.Connection = conn;
using (var da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
}
}
}
any alternative approach for reading?I have tried with stream but same error.
Error is appearing at con.Open()
How can I get list name from Excel file? My actual script for read from Excel is this:
DataSet da = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter();
string name = "PP_s_vypocty"; // I actually using manualy name for read, but i want extract name from file.
string FileName = fullpath;
string _ConnectionString = string.Empty;
string _Extension = Path.GetExtension(FileName);
// Checking for the extentions, if XLS connect using Jet OleDB
if (_Extension.Equals(".xls", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties=Excel 8.0", FileName);
}
// Use ACE OleDb
else if (_Extension.Equals(".xlsx", StringComparison.CurrentCultureIgnoreCase))
{
_ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", FileName);
}
OleDbConnection con = new OleDbConnection(_ConnectionString);
string strCmd = "SELECT J38 FROM " + name;
OleDbCommand cmd = new OleDbCommand(strCmd, con);
try
{
con.Open();
da.Clear();
adapter.SelectCommand = cmd;
adapter.Fill(da);
UniqueValue.money.Add(double.Parse(da.ToString()));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
con.Close();
}
I want to extract name from excel list without manually definition.
You can use OleDbConnection.GetSchema that return a datatable with the list of tables (excel worksheet in your case) that the database contains
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();
}
}