For the purpose of this query please regard an individual Exel worksheet as a 'table'.
Having coded this I find that the Jet4.0 Excel Database engine in conjunction with the ADO datareader object, does not interpret the 'table' in the same way as the COM interop interfaces. The problem being that where a cell contains a "," (comma) the ADO datareader interprets that cell as two cells.
Eg "16, The Ridings" is interpretted as two cells even though when viewed in Excel it is in one cell. This means that when I save the file as a comma delimited CSV some of the rows have more cells than others - I am unable to figure out how to override this undesirable behaviour and wondered if anyone has come across this problem (and solved it)
Here is the basics of the code:
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = conn;
using (DbCommand command = connection.CreateCommand()){
//Create a directory based on the Spreadsheet name to store the csv versions of the worksheets string newDirectory = _fileNameandPath.Remove(_fileNameandPath.LastIndexOf(".")); if (!Directory.Exists(newDirectory)) Directory.CreateDirectory(newDirectory); foreach (string workSheetName in _workSheets){
//Create a csv file for this worksheet StreamWriter sw = File.CreateText(newDirectory + "\\" + workSheetName + ".csv"); // Worksheets are referenced by their worksheet names // We require all rows from the worksheetcommand.CommandText =
"SELECT * FROM [" + workSheetName + "$]"; if (connection.State != ConnectionState.Open)connection.Open();
StringBuilder dataLine = new StringBuilder(); //Populate the DataReader with data from the worksheet using (DbDataReader dr = command.ExecuteReader()){
while (dr.Read()){
//Reset the string builderdataLine.Remove(0, dataLine.Length);
dr.
for (int i = 0; i < dr.FieldCount; i++){
dataLine.Append(dr[i]);
if(i != dr.FieldCount - 1)dataLine.Append(
",");}
sw.WriteLine(dataLine);
}
sw.Close();
}
}
}
}
Peter ByrnePosted Oct 12, 2006, 8:41 PM
ADO doesn't put a delimiter around it's strings. Excel needs them to keep strings containing commas in a single cell - Why should ADO add delimiters? - Of course it should not!
The solution:
replace this:
dataLine.Append(dr[i]);
with this:
dataLine.Append("\"" + dr[i] + "\"");
If any one tried to figure this out then thanks for having a go - Its one of those Gotchas that is glaringly obvious when you know the answer but not so obvious when you dont :)