Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am working on attendance software and my project is almost done, I have just one issue while exporting Datagridview data in excel and it's also working fine just but it does not save the whole header of Datagridview columns please check out the screenshot and please help me how can I do this thanks here is my full header of Datagridview https://imgur.com/8ZdEOd0 here is the screenshot of my excel file after export https://imgur.com/L2IypZZ

What I have tried:

C#
private void ToCsV(DataGridView dGV, string filename)
        {
            string stOutput = "";
            // Export titles:
            string sHeaders = "";

            for (int j = 0; j < dataGridView4.Columns.Count; j++)
                sHeaders = sHeaders.ToString() + Convert.ToString(dataGridView4.Columns[j].HeaderText) + "\t";
            stOutput += sHeaders + "\r\n";
            // Export data.
            for (int i = 0; i < dataGridView4.RowCount; i++)
            {
                string stLine = "";
                for (int j = 0; j < dataGridView4.Rows[i].Cells.Count; j++)
                    stLine = stLine.ToString() + Convert.ToString(dataGridView4.Rows[i].Cells[j].Value) + "\t";
                stOutput += stLine + "\r\n";
            }
            Encoding utf16 = Encoding.GetEncoding(1254);
            byte[] output = utf16.GetBytes(stOutput);
            FileStream fs = new FileStream(filename, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(output, 0, output.Length); //write the encoded file
            bw.Flush();
            bw.Close();
            fs.Close();
        }
        private void button6_Click(object sender, EventArgs e)
        {

            string months = dateTimePicker1.Value.ToString("MMMM");
            string Years = dateTimePicker1.Value.ToString("yyyy");
                ToCsV(dataGridView1, @"D:\"+months+""+" "+""+Years+".xls")
}
Posted
Updated 7-Apr-19 21:31pm
v2

1 solution

The debugger is your friend.

C#
Debug.WriteLine( sHeaders );
 
Share this answer
 
Comments
Member 9983063 8-Apr-19 0:20am    
where I add Debug.WriteLine( sHeaders );

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900