When exporting my data from sql to excel, it starts with the second line and not the first. I think I've narrowed down the problem to the streamwriter section of code but can't seem to work out where it's going wrong! This is the code;
public static void ToCsv3(IDataReader myReader, string fileName, bool includeHeaderAsFirstRow)
{
const string Separator = ",";
Stream s = File.Create(fileName + ".txt");
StreamWriter streamWriter = new StreamWriter(s, Encoding.Unicode);
StringBuilder sb = null;
if (includeHeaderAsFirstRow)
{
sb = new StringBuilder();
for (int index = 0; index < myReader.FieldCount; index++)
{
if (myReader.GetName(index) != null)
sb.Append(myReader.GetName(index));
if (index < myReader.FieldCount - 1)
sb.Append(Separator);
}
streamWriter.WriteLine(sb.ToString());
}
int j = 0;
while (myReader.Read())
{
sb = new StringBuilder();
for (int index = 0; index < myReader.FieldCount - 1; index++)
{
if (!myReader.IsDBNull(index))
{
string value = myReader.GetValue(index).ToString();
if (myReader.GetFieldType(index) == typeof(String))
{
if (value.IndexOf("\"") >= 0)
value = value.Replace("\"", "\"\"");
if (value.IndexOf(Separator) >= 0)
value = "\"" + value + "\"";
}
if (j != 0)
{
if (index == 0)
{
sb.Append(Environment.NewLine);
}
}
sb.Append(value);
j = j + 1;
}
if (index < myReader.FieldCount - 1)
sb.Append(Separator);
}
if (!myReader.IsDBNull(myReader.FieldCount - 1))
sb.Append(myReader.GetValue(myReader.FieldCount).ToString().Replace(Separator, " "));
streamWriter.Write(sb.ToString());
}
myReader.Close();
streamWriter.Close();
}
includeHeaderAsFirstRowistrueor is it that data is being written to the file starting at line 2 and not line 1 even if it's the header?streamWriter.Write(sb.ToString())has written an emptystring? It certainly looks as though it may be possible without knowing your DB fields and data returned.