I'm having to write a program that reads from an Excel file and places it into a DataTable
to export to another Excel file with changed column headers. The data within the columns should stay the same. I'm currently able to get it to the DataTable
, although, I have a ton of information missing (individual cells are left empty/null).
Here is what my Excel file looks like:
+----------------------------------------------+
| ID | AccNum | CustName | City | State |
+----------------------------------------------+
| 02345 | 065812 | CustName1 | City1 | KS |
| 02346 | 087425 | CustName2 | City2 | MO |
| 02347 | 054785 | CustName3 | City3 | KS |
| ..... | ...... | ......... | ..... | .. |
+----------------------------------------------+
Code so far for reading Excel to DataTable
:
public DataTable ReadExcel(string fileName, string TableName)
{
//Creates new DataTable for results
DataTable table = new DataTable();
//Creates connection string for Excel file
OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0\"");
//Creates command to be ran
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + TableName + "$]", connection);
try
{
//Launches connection
connection.Open();
//Creates and Executes data reader
OleDbDataReader reader = cmd.ExecuteReader();
//Loop until the reader closes
while (!reader.IsClosed)
{
//Load reader data to DataTable
table.Load(reader);
}
}
catch (OleDbException ode)
{
Console.WriteLine("ERROR: " + ode.Message);
}
finally
{
//No matter what- close the connection
connection.Close();
}
//Return the DataTable
return table;
}
My expected output is to match the sample Excel file format. However, I'm getting the following:
+----------------------------------------------+
| ID | AccNum | CustName | City | State |
+----------------------------------------------+
| 2345 | 65812 | CustName1 | City1 | KS |
| | 87425 | CustName2 | City2 | MO |
| 2347 | 54785 | CustName3 | City3 | KS |
| ..... | ...... | ......... | ..... | .. |
+----------------------------------------------+
The only data missing is the ID
number along with some leading zeros that are wanting to be kept. With this sample data, for the sake of the length of the post, I've only supplied the three customer
samples. With more data, there are more missing ID
numbers in no particular order.
Am I grabbing the data incorrectly? Is there something I'm missing? I will gladly answer any questions. Thanks in advance.