Click here to Skip to main content
15,901,122 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

How would I be able to import an Excel spreadsheet and be able to save this out to a .DBF file?

I currently have an application that opens the spreadsheet and saves to CSV, is there anyway to change this and save to a Database .DBF file?

My Code:

private string _fileLocation;

        public SpreadsheetApplication()
        {
            InitializeComponent();
        }

        private void btnOpenFile_Click(object sender, EventArgs e)
        {
            //Opens the openfiledialog box so the user can navigate to the spreadsheet. 
            if (openfiledialog.ShowDialog() == DialogResult.OK)
            {
                //Sets the .text property of the text box to be the file selected in the openfiledialog
                txtBxFileLocation.Text = openfiledialog.FileName;
                //Sets the _fileLocation to be the textbox.text value
                _fileLocation = txtBxFileLocation.Text;
            }
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtBxNameFile.TextLength <= 0)
                {
                    MessageBox.Show("Please can you enter a name for the new CSV file.", "Please enter a name", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    //Calls the ConvertExcelToCsv method and sets the arguments (Worksheet argument value is hard coded below)
                    ConvertExcelToCsv(_fileLocation, txtBxNameFile.Text + ".csv");
                }
            }
            catch
            {
                MessageBox.Show("You need to select your spreadsheet.", "Select Spreadsheet", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1)
        {
            //Checks if the two files required exist or not and then throws an exception. 
            if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
            if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

            // connection string for XLS
            var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);

            ///Connection String for XLSX
            //var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=YES\"", excelFilePath);

            //Creates a new OleDbConnection with an argument of cnnStr
            var cnn = new OleDbConnection(cnnStr);

            //creates new datatable in memory to store the read excel spreadsheet.
            var dt = new DataTable();

            try
            {
                //Opens the new connection called "cnn". 
                cnn.Open();
                var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
                string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
                string sql = String.Format("select * from [{0}]", worksheet);
                var da = new OleDbDataAdapter(sql, cnn);
                da.Fill(dt);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                // close resources
                cnn.Close();
            }

            // write out CSV data
            using (var wtr = new StreamWriter(csvOutputFile))
            {
                foreach (DataRow row in dt.Rows)
                {
                    bool firstLine = true;
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
                        var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
                        wtr.Write("\"{0}\"", data);
                    }
                    wtr.WriteLine();

                }
                MessageBox.Show("Spreadsheet has finished processing.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}


Any help is gratefully appreciated.

Regards,

Glen
Posted

1 solution

Hey there Glen,
Not sure if there is an easy way of direct conversion but you could try this:

1. Open Excel as database
C#
string connection_string = @"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=C:\file.xls;ReadOnly=1;ColNameHeader=False";
OdbcConnection oConnection = new OdbcConnection(connection_string);
oConnection.Open();
string SQLstr = "SQL code to read your xls file";
OdbcCommand oCommand = new OdbcCommand(SQLstr, oConnection);
OdbcDataReader dReader = oCommand.ExecuteReader();
while (dReader.Read())
{
   //read data and form internal store (each loop reads 1 line)
}

2. Read it into internal storage (could be some generic List<t>, where T could be your data structure)
XML
List<your_structur> myStorage = new List<your_structure>();
while (dReader.Read())
{
   myStorage.Add(dReader.GetValue(0), dReader.GetValue(1), .... );
}</pre></your_structure></your_structur>


3. Create the DBF (or other database file) and insert the data from your List<t> into the newly create DBF database.
http://stackoverflow.com/questions/3641510/how-to-create-a-dbf-file-using-c[^]

I've done exactly the same as you need to do except that I needed to insert everything into MS SQL server and the approach defined above worked just fine. Hope it's give you a hand as well.

Cheers!

Modestas
 
Share this answer
 
Comments
Glen Childs 30-Sep-13 11:32am    
Thanks Modestas, dont suppose you can help, I have tried the above and I am getting the following error: An OLE DB Provider was not specified in the ConnectionString. An example would be, 'Provider=SQLOLEDB;'. this error is happening on the following line of code: var cnn = new OleDbConnection(cnnStr);

Any suggestions?

Cheers,

Glen.
MK-Gii 1-Oct-13 10:10am    
Mate - I think you're using wrong example. In the example above I am using ODBC and from the error message you gave it looks like you tried OleDB.
And if I were you - I would not use generic approach with var - stringly typed variables usually gives more convenience with intelisence.
Besides - what time zone you're on? I am on GMT+2. If you like - I could give you a hand via Skype and TeamViewer. My skype is Modestas20.
Glen Childs 3-Oct-13 4:42am    
Oops good point! When I changed from OleDB to ODBC it works fine!

Thanks for your help Modestas! :-)
MK-Gii 3-Oct-13 5:11am    
Anytime :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900