0

It's my first time to work with c# and I have a task to create a simple Console Application where you simply just click the program button created in the debug file and then export an amount data from the Stored Precedure I created in the database to an Excel file. My Methode looks like this :

    static void Main(string[] args)
    {
        string path = @"\Users\sa\mydocuments\test.xls";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                //creating the file contents
            }
        }
        using (StreamWriter sw = File.CreateText(path))
        {
            SqlConnection cn = new SqlConnection("Data Source=server1234;Initial Catalog=MySqlDatabase;Integrated Security=True;Trusted_Connection=True");
            SqlCommand cmd = new SqlCommand("MySqlDataBase.dbo.sp_export_data", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                cn.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    sw.WriteLine(dr["name"].ToString() + "\t" + dr["size"].ToString());
                }

                Console.WriteLine("Database has been exported.");
            }
            catch (Exception excpt)
            {
                Console.WriteLine(excpt.Message);
            }

        }
    }

My program runs and creates an excel file, the problem is it's empty and I have no idea if my code is wrong because im not getting any errors. Not sure if im missing anything in my connectionString etc.

Maybe someone could help me out with this or link to how create an export function for Console Application with stored precedures.

pancake
  • 590
  • 7
  • 24

1 Answers1

0

In order to write to Excel files, you'll need to use an Excel library (either the Microsoft Library or a 3rd party).

See here - Creating xls/xlsx files in c#

Community
  • 1
  • 1
Zack Kay
  • 454
  • 3
  • 8