Question

LANGUAGE: C#, System: Windows7, Excel 2007

I want to create a .DBF from some data, and i want to open it from Excel 2007. It can be either dBase or foxpro. I am currently doing in FoxPro9 (btw this code is from the internet):

 OleDbConnection con = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=C:\\Temp\\;");
            con.Open();
            OleDbCommand cmd1 = new OleDbCommand("Create Table TestDBF (Field1 I, Field2 C(10))", con);
            OleDbCommand cmd2 = new OleDbCommand("Insert Into TestDBF Values (1, 'Hello')", con);
            OleDbCommand cmd3 = new OleDbCommand("Insert Into TestDBF Values (2, 'World')", con);
            cmd1.ExecuteNonQuery();
            cmd2.ExecuteNonQuery();
            cmd3.ExecuteNonQuery();
            con.Close();

This generates the file, which i can open in DbfViewer, however, i cant open it in Excel 2007 nor use in some applications i have. I can manually convert the FoxPro .dbf to a dbaseIII dbf using the DbfViwer, but i want it to be automatic.

Any ideas?

Thanks in advance

Was it helpful?

Solution

Here's a little console app that will create a DBF using the CREATE TABLE SQL syntax and then copy it to a previous version of the FoxPro DBF file format that can be opened in Excel.

static void Main(string[] args)
{
    Console.WriteLine("Starting program execution...");

    string connectionString = @"Provider=VFPOLEDB.1;Data Source=C:\YourDirectory\";

    using (OleDbConnection connection = new OleDbConnection(connectionString))
    {
        using (OleDbCommand scriptCommand = connection.CreateCommand())
        {
            connection.Open();

            string vfpScript = @"Create Table TestDBF (Field1 I, Field2 C(10))
                                USE TestDBF
                                COPY TO OpensWithExcel TYPE Fox2x
                                USE";

            scriptCommand.CommandType = CommandType.StoredProcedure;
            scriptCommand.CommandText = "ExecScript";
            scriptCommand.Parameters.Add("myScript", OleDbType.Char).Value = vfpScript;
            scriptCommand.ExecuteNonQuery();
        }
    }

    Console.WriteLine("End program execution...");
    Console.WriteLine("Press any key to continue");
    Console.ReadLine();
}

}

OTHER TIPS

From VFP directly, its easy...

use YourTable
Copy To SomeFile type XLS
        OleDbConnection con = new OleDbConnection("Provider=VFPOLEDB.1;Data Source=C:\\Temp\\;");
        con.Open();
        OleDbCommand cmd1 = new OleDbCommand("Create Table TestDBF (Field1 I, Field2 C(10))", con);
        OleDbCommand cmd2 = new OleDbCommand("Insert Into TestDBF Values (1, 'Hello')", con);
        OleDbCommand cmd3 = new OleDbCommand("Insert Into TestDBF Values (2, 'World')", con);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top