I tried to convert excel file to XML file. And I did it successfully. However when I run the APP on another PC (where I dont have SQL server manager), it is not working anymore. I receive this error
'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine
which I tried to solve with every solved question here (installing Microsoft Access Database Engine 2016 Redistributable, converting app into x86, etc...) and nothing worked.
But since I don't really need (or at least I think so) Access, is there any other way, how to convert excel file to xml?
Here is to code
XmlDocument doc = new XmlDocument();
try
{
bool test = Environment.Is64BitProcess;
FileName.Content = filelocation.Substring(filelocation.LastIndexOf(#"\")+1);
if (!test)
{
connStr = "Provider=Microsoft.ACE.OLEDB.16.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}
OleDbConnection conn = new OleDbConnection(connStr);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
To here it is working, here is the issue
conn.Open();
DataTable dtSheet = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetName = dtSheet.Rows[0]["table_name"].ToString();
cmd.CommandText = "select * from [" + sheetName + "]";
da.SelectCommand = cmd;
da.Fill(dt);
conn.Close();
And then I continue...
DataSet ds = new DataSet();
ds.Tables.Add(dt);
oItem = dt.Rows.Count;
oItem -= 1;
XmlDeclaration declaire = doc.CreateXmlDeclaration("1.0", "utf-8", null);
declaire.Standalone = "yes";
XmlElement rootnode = doc.CreateElement("Wiring");
doc.InsertBefore(declaire, doc.DocumentElement);
doc.AppendChild(rootnode);
while (i <= oItem)
{
XmlElement dobEle = doc.CreateElement("Machine");
do
{...
Is there any other way how to solve the problematic code?
EDIT
I have installed Office on both PCs. And I have tried .Ace.OLEDB.x (4-23 [just to be sure]) and on PC where I develop the APP v.12 and v.16 works. On the PC where I deployed the app none of them works
Edit 2 So I just found out I have office 365 on the 2nd computer but not fully licensed Access (for whatever reason). Could someone confirm, if that's the reason why it doesn't work?
simple and easy excel file reader.
https://github.com/ExcelDataReader/ExcelDataReader
i believe u can also add it from nuget
Related
Hi I am having some issues reading a CSV file with the Jet Database engine. I get this message:
The Microsoft Jet database engine cannot open the file 'C:\Users\mikec\Desktop\'. It is already opened exclusively by another user, or you need permission to view its data.
I have permission to access this folder and file. I have also tried putting in my Visual Studio project and still get the same error. This is my code
string path = #"C:\Users\mikec\Desktop\Book1.csv";
string full = Path.GetFullPath(path);
string file = Path.GetFileName(full);
string dir = Path.GetDirectoryName(full);
//create the "database" connection string
string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=\"" + dir + "\\\";"
+ "Extended Properties=\"Excel 8.0;HDR=Yes;FMT=Delimited\"";
//create the database query
string query = "SELECT * FROM " + file;
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
OleDbConnection con = new OleDbConnection(connString);
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, con);
try
{
//fill the DataTable
dAdapter.Fill(dTable);
}
catch (InvalidOperationException e)
{
}
I'm confused to why this is happening I've looked around the Internet and cannot find a solution.
It would be great if anyone out there could point me in the right direction.
Thanks.
I'm currently facing a problem whereby I don't know how to fix it.
I upload my precompiled project into IIS. Here is my purpose of this page:
User upload a excel file into a folder in the server. ex #"~/PlanQuantityFile/". It did upload successfully.
Problems faced:
It stops when my scripts trying to open the excel file (for extract data purpose) without showing any errors. At line 881 as shown in the image.
Here is few area I had seek for but it still couldn't solve my problem.
Possible Solution:
connection open but never close, so run out of connection. (but I did close it and the scripts stop running before the close statement)
32 bit program calling 64 bit office. (I had limited knowledge on hardware field, don't know what should I do to troubleshoot here)
permission problem. Need to set the permission of ASP.NET account. (I still finding object names for ASP.NET account)
Thanks for anyone who trying to help. Your advice is invaluable.
OleDbConnection oledbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + SaveLocation + ";Extended Properties='Excel 12.0;HDR=YES;IMEX=1;';");
OleDbConnection connExcel = oledbConn;
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
DataTable dt = new DataTable();
cmdExcel.Connection = connExcel;
//Get the name of Sheet
try
{
connExcel.Open();// It stops here without showing errors.
}
catch (Exception ex)
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex.Message + "');", true);
}
The following code returns a datatable for selected filelocation source. Remember to rename the sheetname to "Sheet1".
Use Namespace: using System.Data.OleDb;
Function::::
public DataTable GetExcelinDatatable(string filelocation)
{
DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
OleDbConnection con = new System.Data.OleDb.OleDbConnection(connectionString);
con.Open();
OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter("select * from [SHEET1$]", con);
da.Fill(dt);
con.Close();
return dt;
}
you can use mentioned function to read the Excel file you have to just pass the path of excel file
private List<DataTable> readExcel(string strXLS)
{
//DataTable dtExcel = getExcelSheetTable();
List<DataTable> SheetsData = new List<DataTable>();
DataTable dtExcel = new DataTable();
DataTable SocialMediaExcel = new DataTable();
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strXLS + ";Extended Properties=Excel 12.0;";
try
{
OleDbDataAdapter adpt = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connStr);
adpt.Fill(dtExcel);
SheetsData.Add(dtExcel);
}
catch (Exception ex)
{
throw ex;
}
return SheetsData;
}
I need to connect to a .dbf file in visual Studio using C# and populate a data table. Any ideas? I can currently view the tables in Visual Fox Pro 9.0
Code I have tried and failed, keep getting
External table is not in the expected format.
private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;
void test2()
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
conn.Open();
sqlStr = "Select * from Clients.dbf";
//Make a DataSet object
myDataSet = new DataSet();
//Using the OleDbDataAdapter execute the query
myAdapter = new OleDbDataAdapter(sqlStr, conn);
//Build the Update and Delete SQL Statements
OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);
//Fill the DataSet with the Table 'bookstock'
myAdapter.Fill(myDataSet, "somename");
// Get a FileStream object
FileStream myFs = new FileStream
("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
// Use the WriteXml method of DataSet object to write XML file from the DataSet
// myDs.WriteXml(myFs);
myFs.Close();
conn.Close();
}
This code worked for me!
public DataTable GetYourData()
{
DataTable YourResultSet = new DataTable();
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");
// if including the full dbc (database container) reference, just tack that on
// OleDbConnection yourConnectionHandler = new OleDbConnection(
// "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from CLIENTS"; // dbf table name
OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);
DA.Fill(YourResultSet);
yourConnectionHandler.Close();
}
return YourResultSet;
}
Visual FoxPro DBFs are NOT dBase IV DBFs, and as such are unreadable by most versions of Microsoft Access's Jet database engine. (MSDN has some specifics, if you care.)
You'll need to either export the DBF from FoxPro into an actual dBase format, or you'll need to have C# open it using the Visual FoxPro OLEDB provider.
Once you have the provider installed, you'll need to change the "Provider" argument of your connection string to the following, assuming your DBF is in that folder.
Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\;
(Use an #"" string format; you missed a slash in the code sample, between PC1 and Documents.)
I have a process that allows the user to download a spreadsheet, make some changes, and then upload those changes.
The upload method looks like -
public DataTable ImportXLS(String SourceFilePath) {
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + SourceFilePath + ";" +
"Extended Properties=Excel 8.0;";
using (OleDbConnection cn = new OleDbConnection(ConnectionString)) {
cn.Open();
DataTable dbSchema = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dbSchema == null || dbSchema.Rows.Count < 1) {
throw new Exception("Error: Could not determine the name of the first worksheet.");
}
string WorkSheetName = dbSchema.Rows[0]["TABLE_NAME"].ToString();
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [" + WorkSheetName + "]", cn);
DataTable dt = new DataTable(WorkSheetName);
da.Fill(dt);
return dt;
}
}
When I call the method locally, it works because I can see my local drives.
When deployed to the web server, and called like -
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\Users\mike\Desktop\mike.xls");
I get an error that "C:\Users\mike\Desktop\mike.xls" is not a valid path, obviously because it doesn't exist on the web server.
Has anyone had any experience with trying to upload files over the web and how do you resolve the file location issue?
You need to add a FileUpload control to your Asp.Net page. On a button click you need to the save the file on the server by calling:
FileUpload1.SaveAs("C:\\Uploads\\" + FileUpload1.FileName);
Afterwards you can call you method to process the file
ExportImport _ei = new ExportImport();
DataTable dt = null;
dt = _ei.ImportXLS("C:\\Uploads\\" + FileUpload1.FileName);
So the idea is to upload the file first to the server before processing it.
A link on using the FileUpload control (.Net 2.0)
http://msdn.microsoft.com/en-us/library/aa479405.aspx
You can use Server.MapPath to get the virtual location of your app. Have a look at this article.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am developing on web application that will get the excel file using FileUpload control in asp.net c#. Now when click on submit button, i want to insert the excel data into my database table. I have database in SQL-Server. The field of database table & excel file are same.I want to insert that excel's data into my database table. So how can i do this?
Others have mentioned using Excel interop to read the Excel file in the comments, but this is NOT safe to do for a web application that may have multiple users.
To get started, have a look at the Excel Data Reader project. I've used this several times for processing Excel files from a web application and it works quite well.
You can use OLEDB classes to read directly from Excel file using the Excel drivers in OleDbConnection. Get the data in a datatable and save it to database.
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\\testit.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
// Save your datatable records to DB as you prefer.
I've been testing NPOI as a replacement for another 3rd party Excel parsing library.
https://code.google.com/p/npoi/
So far it seems to work pretty well and have a very complete feature set. Of course, if all you need is very basic Excel data reading (and no writing), then the other DB connection style interfaces mentioned here should work well enough.
EDIT: added sample code
using( FileStream fs = new FileStream("file.xls", FileMode.Open, FileAccess.Read) )
{
HSSFWorkbook wb = new HSSFWorkbook(fs);
double value = wb.GetSheet("Sheet1").GetRow(1).GetCell(1).NumericCellValue;
// read other values as necessary.
}
try the following code . maybe its crude but it works
string connectString =
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\data\\exceltest.xlsx;Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1;\"";
OleDbConnection conn = new OleDbConnection(connectString);
OleDbDataAdapter da = new OleDbDataAdapter("Select * From [Sheet1$]", conn);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
SqlConnection sqlc = new SqlConnection(#"server=.\SQLEXPRESS;user id=sa;pwd=windows;database=exceltest");
sqlc.Open();
SqlCommand cmd = new SqlCommand("select * from table1", sqlc);
SqlDataAdapter sda = new SqlDataAdapter("select * from table1", sqlc);
sda.InsertCommand = new SqlCommand("insert into table1", sqlc);
DataTable dbset = new DataTable();
da.Fill(dbset);
SqlCommand cmdinsert = new SqlCommand();
cmdinsert.Connection = sqlc;
foreach (DataRow dsrc in dt.Rows)
{
string insertcommand = "insert into table1" + dbset.TableName + " ";
string cols = "";
string vals = "";
DataRow dr = dbset.NewRow();
foreach (DataColumn clm in dt.Columns)
{
dr[clm.ColumnName] = dsrc[clm.ColumnName].ToString(); ;
if (cols.Length > 0)
{
cols += ",[" + clm.ColumnName+"]";
}
else
{
cols = "["+clm.ColumnName+"]";
}
if (vals.Length > 0)
{
vals += "," + "'" + dsrc[clm.ColumnName].ToString() + "'";
}
else
{
vals = "'" + dsrc[clm.ColumnName].ToString() + "'";
}
}
insertcommand += "(" + cols + ") values("+vals+")";
cmdinsert.CommandText = insertcommand;
cmdinsert.ExecuteNonQuery();
insertcommand = "";
}
sqlc.Close();