Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all articles
Browse latest Browse all 2535

Export selected rows to Excel from Datagridview using C# winfroms..

$
0
0

Hi Everyone,

  Here am using Datagridview with checkboxes...If I select check boxes and clicks on Export button only Headers were exporting to Excel sheet not the selected rows..could any one tell me what's wrong in my  code..Here I would like to use FOR loop instead of foreach loop because am Exporting images as well to Excel...

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.Filter = "Excel (*.xls)|*.xls";
                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    if (!savefile.FileName.Equals(string.Empty))
                    {
                        FileInfo finfo = new FileInfo(savefile.FileName);
                        if (finfo.Extension.Equals(".xls"))
                        {
                            Excel.Application xlApp;
                            Excel.Workbook xlWorkBook;
                            Excel.Worksheet xlWorkSheet;
                            object misValue = System.Reflection.Missing.Value;

                            xlApp = new Excel.Application();
                            xlWorkBook = xlApp.Workbooks.Add(misValue);
                            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                            int i = 0;
                            int j = 0;

                            for (i = 1; i < dataGridView1.Columns.Count + 1; i++)
                            {
                                xlApp.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText.ToUpper();

                            }

                           if (dataGridView1.SelectedRows == null)
                            {
                                for (i = 0; i < dataGridView1.RowCount; i++) //foreach(DataGridViewRow row in dataGridView1.Rows)
                                {
                                    for (j = 0; j < dataGridView1.ColumnCount; j++)//foreach(DataGridViewCell cell in row.Cells)
                                    {
                                        DataGridViewCell cell = dataGridView1[j, i];
                                        if (cell.GetType() == typeof(DataGridViewImageCell))
                                        {
                                            //j++;
                                            byte[] bimage = (byte[])cell.Value;
                                            MemoryStream ms = new MemoryStream(bimage);
                                            Image image = Image.FromStream(ms);
                                            image.Save(@"D:\image.jpg");
                                            Excel.Range oRange = (Excel.Range)xlWorkSheet.Cells[i + 2, j + 1];
                                            float Left = (float)((double)oRange.Left);
                                            float Top = (float)((double)oRange.Top);
                                            const float ImageSize = 32;
                                            xlWorkSheet.Shapes.AddPicture(@"D:\image.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
                                            oRange.RowHeight = ImageSize + 2;
                                            File.Delete(@"D:\image.jpg");
                                        }
                                        else
                                        {
                                            string s = cell.Value.ToString();
                                           
                                            xlWorkSheet.Cells[i + 2, j + 1] = cell.Value.ToString();
                                        }

                                    }
                                    
                                }
                            }
                            else
                            {
                               for (i = 0; i < dataGridView1.SelectedRows.Count; i++)//not at all executing this loop
                                {
                                    for (j = 0; j < dataGridView1.Columns.Count; j++)
                                    {
                                        DataGridViewCell cell = dataGridView1[j, i];
                                        if (cell.GetType() == typeof(DataGridViewImageCell))
                                        {
                                            //j++;
                                            byte[] bimage = (byte[])cell.Value;
                                            MemoryStream ms = new MemoryStream(bimage);
                                            Image image = Image.FromStream(ms);
                                            image.Save(@"D:\image.jpg");
                                            Excel.Range oRange = (Excel.Range)xlWorkSheet.Cells[i + 2, j + 1];
                                            float Left = (float)((double)oRange.Left);
                                            float Top = (float)((double)oRange.Top);
                                            const float ImageSize = 32;
                                            xlWorkSheet.Shapes.AddPicture(@"D:\image.jpg", Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left, Top, ImageSize, ImageSize);
                                            oRange.RowHeight = ImageSize + 2;
                                            File.Delete(@"D:\image.jpg");
                                        }
                                        else
                                        {
                                            xlWorkSheet.Cells[i + 2, j + 1] = dataGridView1.SelectedRows[i].Cells[j].Value.ToString();
                                        }
                                    }
                                }
                            }

                            xlWorkSheet.Cells.Borders.LineStyle = Excel.XlLineStyle.xlLineStyleNone;
                            //xlWorkSheet.Cells.Borders.LineStyle = Excel.XlBorderWeight.xlMedium;
                            xlWorkSheet.Columns.AutoFit();
                            //xlApp.Visible = true;

                            xlWorkBook.SaveAs(savefile.FileName, 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("Report Generated Successfully", "Sucess", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        }
                        else
                        {
                            MessageBox.Show("Invalid file type", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show("You did pick a location " + "to save file to", "Warning", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                    }
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("Exception Occured,Please Regenerate the Report!" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw ex;
            }  
        }


Thanks & Regards RAJENDRAN M


Viewing all articles
Browse latest Browse all 2535

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>