Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
private void btnexport_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Do you want to save the changes you made to 'Book1'?", "OK", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            if (result.Equals(DialogResult.OK))
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel Documents (*.xls)|*.xls";
                sfd.FileName = "Book1.xls";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    ToCsV(dgvEmpListing, sfd.FileName); // Here dgvEmplisting is grid view name 
                    MessageBox.Show("Document exported successfully");
                }
            }
        }
        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();
        }  
Posted
Comments
[no name] 7-Apr-15 8:33am    
Hai,you want to display all the gridview details into excel ?
Meer Wajeed Ali 7-Apr-15 8:39am    
Yes, I able to display but I want column headings will be there in Excel sheet
[no name] 7-Apr-15 8:42am    
so you want only display gridview column without heading?
Meer Wajeed Ali 7-Apr-15 8:45am    
not at all, I want Company name on top like page heading then Table columns like bold in excel sheet
[no name] 7-Apr-15 8:49am    
you try this type :click here

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