How to Edit / Write in Excel File Sheet (Second Sheet)


Microsoft.Office.Interop.Excel.Application objExcel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook objworkbook;
            Microsoft.Office.Interop.Excel.Worksheet objworksheet;
            try
            {
 
                objExcel.DisplayAlerts = false;
                objExcel.Visible = false;
                Range objRange = null;
                int row = 1, col = 1;
                objworkbook = objExcel.Workbooks.Open(newFilePath, true, false,
                                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                                                      Type.Missing, Type.Missing, true, Type.Missing,
                                                      Type.Missing, Type.Missing, Type.Missing, Type.Missing);               
                objworksheet = (Microsoft.Office.Interop.Excel.Worksheet)objworkbook.Sheets.get_Item("Sheet2");
                int j = col;
                for (int i = 0; i < Mastrerfieldname.Length; i++)
                {
                    objRange = (Range)objworksheet.Cells[row, j];
                    objRange.Value2 = Mastrerfieldname[i].ToString();
                    objRange.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.White);
                    objRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.DarkBlue);
                    j++;
                }
                row++;

                objworksheet.Name = "MasterDetails";
                object objOpt = Missing.Value;
                objworkbook.Save();
                objworkbook.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlSaveChanges, Type.Missing, Type.Missing);
                objExcel.Quit();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                objExcel = null;
                objworkbook = null;
                objworksheet = null;
                ReleaseComObject(objExcel);
                ReleaseComObject(objworkbook);
                ReleaseComObject(objworksheet);
            }

 //Release COM objects from memory
public void ReleaseComObject(object reference)
{
try
{
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(reference) <= 0)
{
}
}
catch
{
}
}
}

Up Next
    Ebook Download
    View all
    Learn
    View all