Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello friends,

I have very big problem in C#.

I have Exported the Data Grid view into Excel but the column name is not exported and I don't know how I can export the Column name.

I'm showing you the code now, if you could just tell me where my mistake is...


C#
// code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
using System.IO;
using MySql.Data.MySqlClient;
using System.Reflection;

namespace PolicySoft
{
    public partial class ExportDateWise : Form
    {
        
        private DataSet ds;

        public ExportDateWise()
        {
            InitializeComponent();
        }


        public void DataGridViewExport(String filepath)
        {
            Excel.Application xlApp;
            Excel.Workbook xlWorkBook;
            Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlApp = new Excel.ApplicationClass();
            xlWorkBook = xlApp.Workbooks.Add(misValue);
            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            int i = 0;
            int j = 0;
            for (i = 0; i <= gv_show_dateWiseDetails.RowCount - 1; i++)
            {
                for (j = 0; j <= gv_show_dateWiseDetails.ColumnCount - 1; j++)
                {
                    DataGridViewCell cell = gv_show_dateWiseDetails[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
                }
            }
            xlWorkBook.SaveAs(filepath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Export SuccessFully");
        }
        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);

                obj = null;
            }
            catch (Exception ex)
            {

                obj = null;

                MessageBox.Show("Exception Occured while releasing object " + ex.ToString());

            }
            finally
            {

                GC.Collect();
            }
        }

        private void btn2Excel_Click(object sender, EventArgs e)
        {

            saveFileDialog1.Filter = "Excel (*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (!saveFileDialog1.FileName.Equals(String.Empty))
                {
                    FileInfo f = new FileInfo(saveFileDialog1.FileName);
                    if (f.Extension.Equals(".xls"))
                    {
                        DataGridViewExport(saveFileDialog1.FileName);
                    }
                    else
                    {
                        MessageBox.Show("Invalid file type");
                    }
                }
                else
                {
                    MessageBox.Show("You did pick a location to save file to");
                }
            }
        }
         
        private void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                ds = new DataSet();
                MySqlConnection con1 = new MySqlConnection(StartUp.database);
                con1.Open();
                string str = "call ps_show_details_date_wise('" + dtp_fromDate.Value.ToString("yyyy-MM-dd") + "','" + dtp_toDate.Value.ToString("yyyy-MM-dd") + "')";
                MySqlDataAdapter da = new MySqlDataAdapter(str, con1);
                da.Fill(ds, "t_transaction");
                gv_show_dateWiseDetails.DataSource = ds.Tables[0];
                gv_show_dateWiseDetails.ReadOnly = true;
                con1.Close();
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}

:(
Posted
Updated 18-Aug-10 0:15am
v3

You need to render the column headers, similar to the example here

http://www.dotnetspark.com/kb/436-convert-datatable-to-csv-file-using-c-sharp.aspx[^]

That is working with a data table + csv, but the principal is the same.

First, write the column names out from your source (DataTable, Gridview, whatever). Then iterate through each row.
 
Share this answer
 
Comments
Dalek Dave 18-Aug-10 6:15am    
Edited for Syntax and Grammar.
Hi naim khan,


http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/27a9002e-9d53-440d-9750-e6c64406fdd6/[^]

This link helpful to you and also you get any idea.

Your are missing a loop for add a column name from datagridview in before set a value.

Thanks.
 
Share this answer
 

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