Click here to Skip to main content
14,699,719 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i Try this this Code in Export Data in Excel
but Problem is Data Export Only Column Header And First Row of DataGridView

What I have tried:

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

            for (int j = 0; j < dGV.Columns.Count; j++)
                sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
            stOutput += sHeaders + "\r\n";
            // Export data.
            for (int i = 0; i < dGV.RowCount - 1; i++)
            {
                string stLine = "";
                for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
                    stLine = stLine.ToString() + Convert.ToString(dGV.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 button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Excel Documents (*.xls)|*.xls";
            sfd.FileName = "export.xls";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                //ToCsV(dataGridView1, @"c:\export.xls");
                ToCsV(dataGridView1, sfd.FileName); // Here dataGridview1 is your grid view name
            }
        }
Posted
Updated 5-Jun-20 3:08am
v2
Comments
Maciej Los 5-Jun-20 6:30am
   
Have you tried to debug?

Firstly, why are you calling ToString on existign strings?
string sHeaders = "";

for (int j = 0; j < dGV.Columns.Count; j++)
    sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";

string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
    stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";


Secondly, we can't help you - we don;t have any access to yoru DGV, and you need that to check what is going on.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
   
Quote:
but Problem is Data Export Only Column Header And First Row of DataGridView

I am not user of DataGridView, but there is something surprising.
If dGV.Columns.Count is correct, I would expect to have dGV.Rows.Count, and not dGV.RowCount.
   
v2
Comments
Richard MacCutchan 5-Jun-20 7:15am
   
dGV.RowsCount should be dGV.Rows.Count.
Patrice T 5-Jun-20 10:59am
   
Good catch, thank you
You cannot create Excel files with a streamwriter. You need to use the OLEDB interface with the Microsoft Access Database Engine 2016 Redistributable from Official Microsoft Download Center[^], or the Microsoft.Office.Interop.Excel Namespace | Microsoft Docs[^].

Also, csv files should not be created with a .xls extension. And their content fields should be separated by commas.
   
Comments
Maciej Los 5-Jun-20 8:56am
   
5ed!
In addition to solution #1 and #2.

Strings are immutable, which means that...
Quote:
...cannot be changed after they have been created. All of the String methods and C# operators that appear to modify a string actually return the results in a new string object.

See: Strings - C# Programming Guide | Microsoft Docs[^]

I'd suggest to use StringBuilder Class (System.Text) | Microsoft Docs[^] to create csv content.

private void ToCsV(DataGridView dGV, string filename)
{
    //create an instance of StringBuilder
    StringBuilder sb = new StringBuilder();
    //headers
    string line = string.Join("\t", dGV.Columns.Cast<DataGridViewColumn>().Select(x=>x.ColumnName));
    sb.AppendLine(line);
    //data
    foreach(DataGridViewRow dgvr in dGV.Rows)
    {
        line = string.Join("\t", dGV.Columns.Cast<DataGridViewColumn>().Select(x=>dgvr[x].ToString()));
        sb.AppendLine(line);
    }
   //use sb.ToString() to save csv content to text file
}
   
v3
Comments
[no name] 17-Jun-20 0:58am
   
Hi,
how can v export data with very long string length with word wrap feature from data in the above code.

Please help.
Maciej Los 17-Jun-20 1:59am
   
Have you tried to use above code? What's wrong with that?
[no name] 17-Jun-20 2:08am
   
Yes, i tried, code is working fine but the content is getting skipped to other rows due to which data in excel is not coming in proper header to column .alignment is not proper
Maciej Los 17-Jun-20 2:31am
   
You need to uderstand that exported text in every columns should have the same lenth to be able to display it in tabular form.
A csv (delimited text) file is not used for text presentation (visualization), but for storing some portion of data...
[no name] 17-Jun-20 2:39am
   
ok...got it !!

Thanks :)
[no name] 17-Jun-20 2:42am
   
is there any other way in .net framework 3.5 apart from interop method for excel export??

As Microsoft.Office.Interop.Excel this is not supporting in 3.5 .net framwork

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