Hi I am trying to export a SQL Server Query to Excel using C# and I am having trouble.
This is what I have tried so far...
I am not sure that I am using this code correctly and could use assistance.
I Receive the error.
Object reference not set to an instance of an object. (This is not a duplicate of another question)
Update: I now receieve this error after fixing object reference not set to instance of an object:
ExecuteReader: Connection property has not been initialized.
On y1.CommandText
String connectionString = "";
connectionString = "REMOVED";
String Filename = null;
y1 = new SqlCommand();
y1.CommandText = @"Select * from products.products";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlDataReader dr = y1.ExecuteReader();
using (System.IO.StreamWriter fs = new System.IO.StreamWriter(Filename))
{
// Loop through the fields and add headers
for (int i = 0; i < dr.FieldCount; i++)
{
string name = dr.GetName(i);
if (name.Contains(","))
name = "\"" + name + "\"";
fs.Write(name + ",");
}
fs.WriteLine();
// Loop through the rows and output the data
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
{
string value = dr[i].ToString();
if (value.Contains(","))
value = "\"" + value + "\"";
fs.Write(value + ",");
}
fs.WriteLine();
}
fs.Close();
}
}
Again thank you.