Guest User

Untitled

a guest
Nov 8th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using MySql.Data.MySqlClient;
  11. using Excel = Microsoft.Office.Interop.Excel;
  12.  
  13. namespace check_disp
  14. {
  15. public partial class check6 : Form
  16. {
  17. MySqlConnection myscon = new MySqlConnection("datasource=localhost;port=3306;initial catalog=test;username=root;password=");
  18.  
  19. public check6()
  20. {
  21. InitializeComponent();
  22. }
  23.  
  24. private void check6_Load(object sender, EventArgs e)
  25. {
  26. try
  27. {
  28. MySqlDataAdapter adapt = new MySqlDataAdapter("SELECT * FROM test_tbl", myscon);
  29.  
  30. myscon.Open();
  31.  
  32. DataSet dset = new DataSet();
  33. adapt.Fill(dset, "test_tbl");
  34. dataGridView1.DataSource = dset.Tables["test_tbl"];
  35.  
  36. myscon.Close();
  37. }
  38.  
  39. catch (Exception ex)
  40. {
  41. MessageBox.Show(ex.Message);
  42. }
  43. }
  44.  
  45. private void button1_Click(object sender, EventArgs e)
  46. {
  47. Excel.Application xlApp;
  48. Excel.Workbook xlWorkBook;
  49. Excel.Worksheet xlWorkSheet;
  50. object misValue = System.Reflection.Missing.Value;
  51.  
  52. xlApp = new Excel.Application();
  53. xlWorkBook = xlApp.Workbooks.Add(misValue);
  54. xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
  55. int i = 0;
  56. int j = 0;
  57.  
  58. for (i = 0; i <= dataGridView1.RowCount - 1; i++)
  59. {
  60. for (j = 0; j <= dataGridView1.ColumnCount - 1; j++)
  61. {
  62. DataGridViewCell cell = dataGridView1[j, i];
  63. xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;
  64. }
  65. }
  66.  
  67. xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
  68. xlWorkBook.Close(true, misValue, misValue);
  69. xlApp.Quit();
  70.  
  71. releaseObject(xlWorkSheet);
  72. releaseObject(xlWorkBook);
  73. releaseObject(xlApp);
  74.  
  75. MessageBox.Show("Excel file created , you can find the file c:\csharp.net-informations.xls");
  76. }
  77.  
  78. private void releaseObject(object obj)
  79. {
  80. try
  81. {
  82. System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
  83. obj = null;
  84. }
  85. catch (Exception ex)
  86. {
  87. obj = null;
  88. MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
  89. }
  90. finally
  91. {
  92. GC.Collect();
  93. }
  94. }
  95. }
  96. }
  97.  
  98. xlApp = new Excel.Application();
Add Comment
Please, Sign In to add comment