3
Answers

how to add column in excel using C#

narasiman rao

narasiman rao

8y
277
1
string connectionstring = "Server=(local);initial catalog=Test;Trusted_Connection=True";
SqlConnection sqlConnection = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
DataSet ds = new DataSet();
cmd.CommandText = "select * from Empdetails";
cmd.CommandText += " where shifttype = @par ";
cmd.Parameters.Add("@par", SqlDbType.Int).Value = j;
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection;
sqlConnection.Open();
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
System.IO.StreamWriter sw_In = new System.IO.StreamWriter(@"C:\Users\God\Desktop\DataDump\" + j + "Excel.xls");
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
sw_In.AutoFlush = true;
sw_In.Write(reader[i].ToString() + "\t");
}
sw_In.Write("\n");
}
}
sqlConnection.Close();
reader.Close();
When i  run the above code in excel record as follows 
     1    Suresh    9867689098    IN   Chennai  
     2    Rajesh    9840512112    IN   Chennai   
     3    Vikash    9844521213    IN   Chennai  
     4    Ramesh    9955454213    IN   Chennai 
     5    Kumar     9840521210    IN   Chennai
 
But  in table select * from Empdetails record as follows with column name 
       ID     Name           Mobile       Shift        Place
    1    Suresh    9867689098    IN   Chennai  
    2    Rajesh    9840512112    IN   Chennai   
    3    Vikash    9844521213    IN   Chennai  
    4    Ramesh    9955454213    IN   Chennai 
    5    Kumar     9840521210    IN   Chennai
In excel the above column to be there.
 for that how can i do in asp,net using C#.   
in excel with column name records to be there.



Answers (3)