I want to read a simple foxpro dbf file and convert it into xml file and save it into my pc.
Is it possible to read and convert simple file.DBF with out using any db connection?
Yes, It is possible. Create connection on DBF table as appropriate based on this link http://www.connectionstrings.com/dbf-foxpro. Later you get the entire data onto a Dataset. You can save data set wherever you want to in XML format.
Here is the code...
private void btnBrowse_Click(object sender, EventArgs e)
{
try
{
var path = "F:\\Projects\\dbf"; // Path of the folder containing dbf file.
var fileName = "Invoices1.dbf";
var constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=DBASE III";
var sql = "select * from " + fileName;
var ds = new DataSet();
using (var con = new OleDbConnection(constr))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
using (var da = new OleDbDataAdapter(cmd))
{
da.Fill(ds);
dataGridView1.DataSource = ds.Tables.Count > 0
? ds.Tables[0].Copy() : new DataTable();
}
}
}
}
catch
{
throw;
}
}
Related
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
I have a Foxpro .DBF file. I am using OLEDB driver to read the .DBF file. I can query the DBF and utilize its .CDX index file(cause it is automatically opened). My problem is that I want to query it with the .NDX index file (which is not automatically opened when the .DBF is opened). How can I open the .NDX file in C# using OLEDB driver cause the DBF is really big to search for a record without the index? Thanks all! Here is the code I am using to read the DBF.
OleDbConnection oleDbConnection = null;
try
{
DataTable resultTable = new DataTable();
using (oleDbConnection = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=P:\\Test\\DSPC-1.DBF;Exclusive=No"))
{
oleDbConnection.Open();
if (oleDbConnection.State == ConnectionState.Open)
{
OleDbDataAdapter dataApdapter = new OleDbDataAdapter();
OleDbCommand command = oleDbConnection.CreateCommand();
string selectCmd = #"select * from P:\Test\DSPC-1 where dp_file = '860003'";
command.CommandType = CommandType.Text;
command.CommandText = selectCmd;
dataApdapter.SelectCommand = command;
dataApdapter.Fill(resultTable);
foreach(DataRow row in resultTable.Rows)
{
//Write the data of each record
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally
{
try
{
oleDbConnection.Close();
}
catch (Exception e)
{
Console.WriteLine("Failed to close Oledb connection: " + e.Message);
}
}
ndx files wouldn't be opened by default and those are a thing of the past really, why wouldn't you simply add your index to your CDX. If it is not an option, then ExecScript suggestion by DRapp is what you can do. He was very close. Here is how you could do that:
string myCommand = #"Use ('P:\Test\DSPC-1') alias myData
Set Index To ('P:\Test\DSPC-1_Custom.NDX')
select * from myData ;
where dp_file = '860003' ;
into cursor crsResult ;
nofilter
SetResultset('crsResult')";
DataTable resultTable = new DataTable();
using (oleDbConnection = new OleDbConnection(#"Provider=VFPOLEDB;Data Source=P:\Test"))
{
oleDbConnection.Open();
OleDbCommand command = new OleDbCommand("ExecScript", oleDbConnection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("code", myCommand);
resultTable.Load(cmd.ExecuteReader());
oleDbConnection.Close();
}
Your connection string should only reference the PATH to where the .dbf files are located.
Then, your query is just by the table name.
new OleDbConnection("Provider=VFPOLEDB.1;Data Source=P:\\Test\\;Exclusive=No"))
selectCmd = #"select * from DSPC-1 where dp_file = '860003'";
As for using the .NDX, how / where was that created... Is that an old dBASE file you are using the Visual Foxpro driver for?
If it is a separate as described, you might need to do via an ExecScript() to explicitly open the file first WITH the index, THEN run your query. This is just a SAMPLE WITH YOUR FIXED value. You would probably have to PARAMETERIZE it otherwise you would be open to sql-injection.
cmd.CommandText = string.Format(
#"EXECSCRIPT('
USE DSPC-1 INDEX YourDSPC-1.NDX
SELECT * from DSPC-1 where dp_file = '860003'" );
Also, you might have issue with your table names being hyphenated, you may need to wrap it in [square-brackets], but not positive if it is an issue.
I have a spreadsheet and I want to upload it in a ASP.NET-MVC tool using C# to extract the data then put them on an SQL server database.
I created a function who put the data into a DataSet so I can use it after to put the data into the database.
Here is the function :
public DataSet getData(HttpPostedFileBase file, string path)
{
var fileName = Path.GetFileName(file.FileName);
oledbConn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"");
DataSet ds = new DataSet();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter oleda = new OleDbDataAdapter();
oledbConn.Open();
cmd.Connection = oledbConn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Worksheet0$]";
oleda = new OleDbDataAdapter(cmd);
oleda.Fill(ds);
oledbConn.Close();
return ds;
}
Everything is working but when I do a foreach on the dataset and retrieve the data there is a formatting problem.
The values in my spreadsheet are formatted as Numbers, so for example 1.25 turns into 1.3. The cell is showing 1.3 but when I click on it the value is 1.25.
When I check on my dataset the values in it are the one formatted (not the real values), I have for example the 1.3 instead the 1.25.
When I change the columns format before uploading, everything works all right ! But I am looking for an automatic process to do that.
I think you should try to change this library. I recommend you to use ExcelDataReader 2.1.2.3 and here is the NuGet for it: https://www.nuget.org/packages/ExcelDataReader/
I used this library, it is very fast, and lightweight library. and here is my code:
public List<Checklist> Provide()
{
List<Checklist> checklists = new List<Checklist>();
using (var reader = ExcelReaderFactory.CreateOpenXmlReader(m_Stream))
{
while (reader.Read())
{
Checklist checklist = new Checklist();
checklist.Description = reader.GetString(1);
checklist.View = reader.GetString(2);
checklist.Organ = reader.GetString(3);
checklists.Add(checklist);
}
return checklists;
}
}
Thanks to #Nadeem Khouri
I used the ExcelDataReaderLibrary
Here is the working code :
public DataSet getData(string path)
{
FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
DataSet result = excelReader.AsDataSet();
return result;
}
Here's my situation. I'm designing a program that takes Excel files (which may be in csv, xls, or xlsx format) from a remote network drive, processes the data, then outputs and stores the results of that process. The program provides a listbox of filenames that are obtained from the remote network drive folder using the method detailed in the accepted answer here. Once the user selects a filename from the listbox, I want the program to find the file and obtain the information from it to do the data processing. I have tried using this method to read the data from the Excel file while in a threaded security context, but that method just fails without giving any kind of error. It seems to not terminate. Am I going about this the wrong way?
Edit - (Final Notes: I have taken out the OleDbDataAdapter and replaced it with EPPlus handling.)
I was able to scrub sensitive data from the code, so here it is:
protected void GetFile(object principalObj)
{
if (principalObj == null)
{
throw new ArgumentNullException("principalObj");
}
IPrincipal principal = (IPrincipal)principalObj;
Thread.CurrentPrincipal = principal;
WindowsIdentity identity = principal.Identity as WindowsIdentity;
WindowsImpersonationContext impersonationContext = null;
if (identity != null)
{
impersonationContext = identity.Impersonate();
}
try
{
string fileName = string.Format("{0}\\" + Files.SelectedValue, #"RemoteDirectoryHere");
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.14.0; data source={0}; Extended Properties=Excel 14.0;", fileName);
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Sheet1", connectionString);
DataSet ds = new DataSet();
adapter.Fill(ds, "Sheet1");
dataTable = ds.Tables["Sheet1"];
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}
Additional Edit
Now xlsx files have been added to the mix.
Third Party
Third party solutions are not acceptable in this case (unless they allow unrestricted commercial use).
Attempts - (Final Notes: Ultimately I had to abandon OleDb connections.)
I have tried all of the different connection strings offered, and I have tried them with just one file type at a time. None of the connection strings worked with any of the file types.
Permissions
The User does have access to the file and its directory.
Your connection string might be the issue here. As far as I know, there isn't 1 that can read all xls, csv, and xlsx. I think you're using the XLSX connection string.
When I read xls, i use the following connection string:
#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Having said that, I recommend using a 3rd party file reader/parser to read XLS and CSV since, from my experience, OleDbDataAdapter is wonky depending on the types of data that's being read (and how mixed they are within each column).
For XLS, try NPOI https://code.google.com/p/npoi/
For CSV, try http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader
For XLSX, try EPPlus http://epplus.codeplex.com/
I've had great success with the above libraries.
Is it really important that you use an OleDb interface for this? I've always done it with Microsoft.Office.Excel.Interop, to wit:
using System;
using Microsoft.Office.Interop.Excel;
namespace StackOverflowExample
{
class Program
{
static void Main(string[] args)
{
var app = new Application();
var wkbk = app.Workbooks.Open(#"c:\data\foo.xls") as Workbook;
var wksht = wkbk.Sheets[1] as Worksheet; // not zero-based!
for (int row = 1; row <= 100; row++) // not zero-based!
{
Console.WriteLine("This is row #" + row.ToString());
for (int col = 1; col <= 100; col++)
{
Console.WriteLine("This is col #" + col.ToString());
var cell = wksht.Cells[row][col] as Range;
if (cell != null)
{
object val = cell.Value;
if (val != null)
{
Console.WriteLine("The value of the cell is " + val.ToString());
}
}
}
}
}
}
}
As you will be dealing with xlsx extension, you should rather opt for the new connection string.
public static string getConnectionString(string fileName, bool HDRValue, bool WriteExcel)
{
string hdrValue = HDRValue ? "YES" : "NO";
string writeExcel = WriteExcel ? string.Empty : "IMEX=1";
return "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + fileName + ";" + "Extended Properties=\"Excel 12.0 xml;HDR=" + hdrValue + ";" + writeExcel + "\"";
}
Above is the code for getting the connection string. First argument expects the actual path for file location. Second argument will decide whether to consider first row values as column headers or not. Third argument helps decide whether you want to open the connection to create and write the data or simply read the data. To read the data set it to "FALSE"
public static ReadData(string filePath, string sheetName, List<string> fieldsToRead, int startPoint, int endPoint)
{
DataTable dt = new DataTable();
try
{
string ConnectionString = ProcessFile.getConnectionString(filePath, false, false);
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.");
}
StringBuilder sb = new StringBuilder();
sb.Append("SELECT *");
sb.Append(" FROM [" + sheetName + fieldsToRead[0].ToUpper() + startPoint + ":" + fieldsToRead[1].ToUpper() + endPoint + "] ");
OleDbDataAdapter da = new OleDbDataAdapter(sb.ToString(), cn);
dt = new DataTable(sheetName);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
string i = row[0].ToString();
}
}
cn.Dispose();
return fileDatas;
}
}
catch (Exception)
{
}
}
This is for reading 2007 Excel into dataset
DataSet ds = new DataSet();
try
{
string myConnStr = "";
myConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=MyDataSource;Extended Properties=\"Excel 12.0;HDR=YES\"";
OleDbConnection myConn = new OleDbConnection(myConnStr);
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$] ", myConn);
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
myConn.Open();
adapter.Fill(ds);
myConn.Close();
}
catch
{ }
return ds;
I have a web application in C# / ASP.NET. I want to export all the database table's data, with the same unique key (Company ID). All the tables have this key (different for every company). I want to do that for future backup. Is it possible with Linq or classic C#? How can achieve this backup and restore?
One of the example to the solution is
using System.Data.SqlClient;
using System.Data;
using System.IO;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
var connStr = "Data Source=MOHSINWIN8PRO\\SQLEXPRESS;Initial Catalog=AB2EDEMO;Integrated Security=True";
var xmlFileData = "";
DataSet ds = new DataSet();
var tables = new[] {"Hospital", "Patient"};
foreach (var table in tables)
{
var query = "SELECT * FROM "+ table +" WHERE (Hospital_Code = 'Hosp1')";
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
conn.Close();
conn.Dispose();
xmlFileData+=ds.GetXml();
}
File.WriteAllText("D://SelectiveDatabaseBackup.xml",xmlFileData);
}
}
}
this will create SelectiveDatabaseBackup.xml which can be later used to restore the backup
SaveFileDialog SD = new SaveFileDialog();
if (SD.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
{
System.IO.StreamWriter SW = new System.IO.StreamWriter(SD.FileName);
foreach (string str in checkedListBox1.CheckedItems)
{
string XMLSTR = //Heads.funtions.ConvertDatatableToXML(
Heads.funtions.fire_qry_for_string(string.Format("Select * from {0} FOR XML AUTO,TYPE, ELEMENTS ,ROOT('{0}')", str)); // , str);
SW.Write(XMLSTR);
SW.WriteLine("###TABLEEND###");
}
SW.Close();
//_CommonClasses._Cls_Alerts.ShowAlert("Clean Up Completed...!!!", "CleanUP", MessageBoxIcon.Information);
}