Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I am exporting the contents of datagridview to excel but while exporting i get the above error. the code is:

C#
private void btn_GenerateXL_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                msgBox.CustomMessage = m_resourceManger.GetString("Background Busy");
                msgBox.MessageType = Constant.Warning;
                msgBox.ShowDialog();
            }
            else
            {
                ShowUIMessage(Constant.Info, m_resourceManger.GetString("ButtonClicked"));
                try
                {
                    if (dgvPopulateData.Rows.Count > 0)
                    {
                        btn_PopulateGrid.Enabled = false;
                        Excel.ApplicationClass excel = null;
                        Excel.Workbook xlWorkBook = null;
                        Excel.Worksheet xlWorkSheetData = null;
                        Excel.Worksheet xlWorkSheetHelp = null;
                        Excel.Range range = null;
                        Excel.Sheets xlWorkSheets = null;
                        Excel.FormatCondition condition = null;
                        Excel.Application xlApp;
                        object misValue = System.Reflection.Missing.Value;
                        excel = new Excel.ApplicationClass();
                        excel.Application.Workbooks.Add(Type.Missing);
                        Int16 i, j;
                        xlWorkBook = excel.Application.Workbooks[1];
                        xlWorkSheets = xlWorkBook.Worksheets;
                        xlWorkSheetData = (Excel.Worksheet)xlWorkSheets.get_Item(1);
                        xlWorkSheetData.Name = "Language_Data";

                        for (i = 1; i < dgvPopulateData.Columns.Count + 1; i++)
                        {
                            xlWorkSheetData.Cells[1, i] = dgvPopulateData.Columns[i - 1].HeaderText;
                        }
                        // storing Each row and column value to excel sheet 
                        for (i = 0; i < dgvPopulateData.Rows.Count - 1; i++)
                        {
                            for (j = 0; j < dgvPopulateData.Columns.Count; j++)
                            {
                                if (!string.IsNullOrEmpty(dgvPopulateData.Rows[i].Cells[j].Value.ToString()) || dgvPopulateData.Rows[i].Cells[j].Value.ToString().Trim().Length == 0)
                                {
                                    continue;
                                }
                                
                                xlWorkSheetData.Cells[i + 2, j + 1] = dgvPopulateData.Rows[i].Cells[j].Value.ToString();// When i's value becomes 2 and comes to above line it shows this error.
                            }
                        }

                        xlWorkBook.SaveAs(@"c:\csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
                        xlWorkBook.Close(true, misValue, misValue);
                        excel.Quit();

                        releaseObject(xlWorkSheetData);
                        releaseObject(xlWorkBook);
                        releaseObject(excel);
                        msgBox.CustomMessage = m_resourceManger.GetString("ExcelGen");
                        msgBox.MessageType = Constant.Info;
                        msgBox.ShowDialog();
                        backgroundWorker1.RunWorkerAsync();
                        btn_PopulateGrid.Enabled = true;
                        ShowUIMessage(Constant.Info, m_resourceManger.GetString("ExcelGen"));
                    }
                    else
                    {
                        ShowUIMessage(Constant.Error, m_resourceManger.GetString("GridEmpty"));
                    }
                }
                catch (Exception Ex)
                {
                    ShowUIMessage(Constant.Error, Constant.ErrorMsg + Ex.Message.ToString());
                }
            }
        }

        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();
            }
        }


-------------------------------------------------------------------------------------
xlWorkSheetData.Cells[i + 2, j + 1] = dgvPopulateData.Rows[i].Cells[j].Value.ToString(); here i am getting the error.

my gridview is like this:-

id   name  department
1     dh     uhu33
2     jej    dvv12
             egfeg12
3     udhf   nsd12
             ndfi23


i want to export it as it is. Help me plz. Thanks in Advance
Posted
Updated 9-Aug-12 3:04am
v3
Comments
[no name] 9-Aug-12 9:01am    
Either rows[i] is null or cells[j] is null. You are off by one probably.

am not sure. But its worth try. You should loop till count-1 here
C#
for (j = 0; j < dgvPopulateData.Columns.Count-1; j++)
{
 
Share this answer
 
v2
Comments
Christian Amado 9-Aug-12 8:49am    
50% of the answer, i think. He has a reference error not index exception. May be xlWorkSheetData or the value of the cell is null.
Amit Roy 9-Aug-12 8:55am    
for (j = 0; j < dgvPopulateData.Columns.Count-1; j++)
{
Again getting same error
Amit Roy 9-Aug-12 8:57am    
2 jej dvv12
egfeg12// getting error due to this row
3 udhf nsd12
ndfi23
Hi,

In the given line of code from where you are getting error,

i.e.
C#
xlWorkSheetData.Cells[i + 2, j + 1] = dgvPopulateData.Rows[i].Cells[j].Value.ToString();


the possibility i can see for the error message is either .Value or .ToString(). You need checking for Null value of
dgvPopulateData.Rows[i].Cells[j]

check if HashValue method available if so , use it to check if data is available. or you can simply check for Null.

So you code would be like,
C#
if(dgvPopulateData.Rows[i].Cells[j] != null)
{
xlWorkSheetData.Cells[i + 2, j + 1] = dgvPopulateData.Rows[i].Cells[j].Value.ToString();
}


Hope this will resolve your issue,

Thanks
-Amit Gajjar.
 
Share this answer
 
Comments
Amit Roy 9-Aug-12 9:22am    
Still the issue is same but i think i am getting error because xlWorkSheetData is null. How to check for it?
AmitGajjar 9-Aug-12 12:58pm    
ok... then you need to add if condition like

if(dgvPopulateData.Rows[i].Cells[j] != null && xlWorkSheetDate != null)
You are taking i from 0 to count-1 and then checking for value .cells[i+2]
 
Share this answer
 
Comments
Amit Roy 10-Aug-12 1:07am    
I think i can't fix this bug...
Since this approach was not working for me. i had to do it using another approach or a simple aproach. Populating the excel column wise one by one. Thank you all who helped me or tried to help me.
 
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