P. 1
Csharp Excel Data Grid View

Csharp Excel Data Grid View

|Views: 7|Likes:
Published by Ajinkya Ragalwar

More info:

Published by: Ajinkya Ragalwar on May 11, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as TXT, PDF, TXT or read online from Scribd
See more
See less

08/01/2011

pdf

text

original

using using using using using

System; System.Windows.Forms; System.Data; System.Data.SqlClient; Excel = Microsoft.Office.Interop.Excel;

namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SqlConnection cnn ; string connectionString = null; string sql = null; connectionString = "data source=servername;initial catalog=databasen ame;user id=username;password=password;"; cnn = new SqlConnection(connectionString); cnn.Open(); sql = "SELECT * FROM Product"; SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn); DataSet ds = new DataSet(); dscmd.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } private void button2_Click(object sender, EventArgs e) { Excel.Application xlApp ; Excel.Workbook xlWorkBook ; Excel.Worksheet xlWorkSheet ; object misValue = System.Reflection.Missing.Value; xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); int i = 0; int j = 0; for (i = 0; i <= dataGridView1.RowCount - 1; i++) { for (j = 0; j <= dataGridView1.ColumnCount - 1; j++) { DataGridViewCell cell = dataGridView1[j, i]; xlWorkSheet.Cells[i + 1, j + 1] = cell.Value; } } xlWorkBook.SaveAs("csharp.net-informations.xls", Excel.XlFileFormat. xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMo de.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(true, misValue, misValue); xlApp.Quit();

releaseObject(xlWorkSheet).Show("Exception Occured while releasing object " + ex . } catch (Exception ex) { obj = null.Collect().Marshal.net-informations.Show("Excel file created . releaseObject(xlApp).InteropServices. } } } } . } private void releaseObject(object obj) { try { System. MessageBox. you can find the file c:\\csha rp. } finally { GC.ToString()).ReleaseComObject(obj). MessageBox.Runtime.xls"). obj = null. releaseObject(xlWorkBook).

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->