Saturday, October 9, 2010

Export DataGridView Data in Excel C#

object misValue = System.Reflection.Missing.Value;


Excel.Application xlapp;

Excel.Workbook xlworkbook;

Excel.Worksheet xlsheets;

xlapp = new Excel.ApplicationClass();

xlworkbook = xlapp.Workbooks.Add("");

xlsheets = (Excel.Worksheet)xlworkbook.Sheets.get_Item(1);

int i = 0; int j = 0;

int x = 2;

for (i = 0; i <= dataGridView1.Rows.Count - 1; i++)

{

for (j = 0; j <= dataGridView1.Columns.Count-1; j++)

{

DataGridViewCell dgvcell = dataGridView1[j, i];

if (i == 0)

{

string ss = "B"+(j+1);

xlsheets.Cells[i + 1, j + 1] = dataGridView1.Columns[dgvcell.ColumnIndex].Name;

//xlsheets.get_Range("A1", "C1").Interior.ColorIndex = 37;

xlsheets.get_Range("A1", "C1").Interior.Color= System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue);

xlsheets.get_Range("A1", "C1").Interior.Pattern = XlPattern.xlPatternSolid;

xlsheets.get_Range("A1", "C1").Font.Bold = true;

xlsheets.get_Range("A1", "C1").HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;

//xlsheets.get_Range("A1", "C1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;



}



xlsheets.Cells[i+2, j+1] = dgvcell.Value;





}

string rng1 = "A" + (i + 2);

string rng2 = "C" + (i + 2);



xlsheets.get_Range(rng1, rng2).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Pink);

xlsheets.get_Range(rng1, rng2).Interior.Pattern = XlPattern.xlPatternSolid;



}

xlworkbook.SaveAs("d:\\MM.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
 
 
 
private void releaseObject(object obj)


{

try

{

System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);

obj = null;

}

catch (Exception ex)

{

obj = null;

MessageBox.Show("Exception Occured while releasing object " + ex.ToString());

}

finally

{

GC.Collect();

}

}
 

No comments:

Post a Comment

Mat Table Angular

Mat Table in Angular Mat table is used to display data . its a material designed styled data-table . For using Material Table MatTableMo...