Guest User

Untitled

a guest
Aug 25th, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. private void button3_Click(object sender, EventArgs e)
  2. {
  3.  
  4. try
  5. {
  6. Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
  7. excel.Visible = true;
  8. Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
  9. Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
  10. int StartCol = 1;
  11. int StartRow = 1;
  12. int j = 0, i = 0;
  13.  
  14. //Write Headers
  15. for (j = 0; j < dataGridView.Columns.Count; j++)
  16. {
  17. Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j];
  18. myRange.Value2 = dataGridView.Columns[j].HeaderText;
  19. }
  20.  
  21. StartRow++;
  22.  
  23. //Write datagridview content
  24. for (i = 0; i < dataGridView.Rows.Count; i++)
  25. {
  26. for (j = 0; j < dataGridView.Columns.Count; j++)
  27. {
  28. try
  29. {
  30. Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j];
  31. myRange.Value2 = dataGridView[j, i].Value == null ? "" : dataGridView[j, i].Value;
  32. }
  33. catch
  34. {
  35. ;
  36. }
  37. }
  38. }
  39. }
  40. catch (Exception ex)
  41. {
  42. MessageBox.Show(ex.ToString());
  43. }
  44.  
  45. }
  46.  
  47. private void button5_Click(object sender, EventArgs e)
  48. {
  49.  
  50.  
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment