Take the 2-minute tour ×

I am working on writing the data into Excel sheet in c#.

I have wriiten the following code.

        string excel_filename = @"C:\Users\Downloads\bookmain.xlsx";
        Excel.Application excel = new Excel.Application();
        excel.Visible = true;
        Excel.Workbook wb = excel.Workbooks.Open(excel_filename);
        Excel.Worksheet sh = wb.Sheets.Add(); 
        sh.Name = "TestSheet"; 
        sh.Cells[1, "A"].Value2 = "SNO";
        sh.Cells[1, "B"].Value2 = "Name";
        sh.Cells[1, "C"].Value2 = "ID";
            sh.Cells[i+2, "A"].Value2 = "1";
            sh.Cells[i+2, "B"].Value2 = "A";
            sh.Cells[i+2, "C"].Value2 = "1122"; 


Here I have given the path of excel file that already exists and it is empty.

How to change this code that, when i give the path it should automatically check, if it exists it have to create otherwise no need to create.

Even my code also need to check sheet name, it it exist i shall directly edit it or else I need to create a new sheet.

Can any one share their response.

Thank you.

share|improve this question
just a recommendation: try EPPlus (epplus.codeplex.com). It is a library to read, modify and create excel 2007/2010 files without the need for Excel automation. You don't need excel installed to use it. –  Dirk Trilsbeek Apr 11 '12 at 9:15

1 Answer 1

up vote 4 down vote accepted

for checking existence of file :

  //if not exists then only create:- 

and for checking worksheet you can do like :

foreach (Sheet sheet in workbook.Sheets)
    if (sheet.Name.equals("Test"))
        //do something

UPDATED : this is how it works :

Create Excel object

Excel.Application excel = new Excel.Application();

make Excel visible

excel.visible = true

add a worksheet

Excel.Worksheet sh = wb.Sheets.Add();

save it as

  wb .SaveAs( @"C:\Users\Downloads\bookmain.xlsx",
            Excel.XlFileFormat.xlXMLSpreadsheet, missing, missing,
            false, false, Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);
share|improve this answer
check the updated code. –  Pranav Apr 11 '12 at 9:14
Can you also say how do i craete it. –  Patan Apr 11 '12 at 9:26
Thank you so much for the information –  Patan Apr 11 '12 at 9:43
Thanks Pranav. This is really very helpfull. –  Patan Apr 11 '12 at 11:48

Your Answer


