Goran Bibic

Goran Bibic

  • 454
  • 2.9k
  • 177.5k

Export to excel c#

Dec 7 2019 1:56 AM
Need to export to excel, on older version excel work on 2019 dont work
 
 
 
I use this code
 
  1. try  
  2.            {  
  3.                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();  
  4.                excel.Visible = true;  
  5.                Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);  
  6.                Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];  
  7.                int StartCol = 1;  
  8.                int StartRow = 1;  
  9.                int j = 0, i = 0;  
  10.   
  11.                //Write Headers  
  12.                for (j = 0; j < (IOSDataGridView.Columns.Count - 1); j++)  
  13.                {  
  14.                    //  if (j == 0 || j == 1 || j == 5 || j == 7 || j == 12)  
  15.                    if (j == 0)  
  16.                    {  
  17.                    }  
  18.                    else  
  19.                    {  
  20.                        Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];  
  21.                        myRange.Value2 = IOSDataGridView.Columns[j].HeaderText;  
  22.                    }  
  23.                }  
  24.   
  25.                StartRow++;  
  26.   
  27.                //Write datagridview content  
  28.                for (i = 0; i < IOSDataGridView.Rows.Count; i++)  
  29.                {  
  30.                    for (j = 0; j < (IOSDataGridView.Columns.Count - 1); j++)  
  31.                    {  
  32.                        try  
  33.                        {  
  34.                            // if (j == 0 || j == 1 || j == 5 || j == 7 || j == 12)  
  35.                            if (j == 0)  
  36.                            {  
  37.                            }  
  38.                            else  
  39.                            {  
  40.                                Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];  
  41.                                myRange.Value2 = IOSDataGridView[j, i].Value == null ? "" : IOSDataGridView[j, i].Value;  
  42.                            }  
  43.                        }  
  44.                        catch  
  45.                        {  
  46.                            ;  
  47.                        }  
  48.                    }  
  49.                }  
  50.            }  
  51.            catch (Exception ex)  
  52.            {  
  53.                MessageBox.Show(ex.ToString());  
  54.            } 
 
 
 
 
 

Answers (2)