Phu Minh Pham
Phu Minh Pham

Reputation: 1055

Creating xls file with too many sheets using Microsoft.Office.Interop.Excel

How do I create only one sheet? What i've done is this:

public static void CreateExcel(string year)
{
    Application xlApp = new Application();
    Workbook xlWorkBook;
    Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;

    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Worksheet)xlWorkBook.Worksheets.Item[1];
    xlWorkSheet.Name = year;
    xlWorkSheet.Cells[1, 1] = "Share";
    xlWorkSheet.Cells[1, 2] = "Q1";
    xlWorkSheet.Cells[1, 3] = "Q2";
    xlWorkSheet.Cells[1, 4] = "Q3";
    xlWorkSheet.Cells[1, 5] = "Q4";

    xlWorkBook.SaveAs(@"H:\\QResults.xls", XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    ReleaseObject(xlWorkSheet);
    ReleaseObject(xlWorkBook);
    ReleaseObject(xlApp);
}

And it creates a xls file with 3 sheets with the first sheet named.

Upvotes: 0

Views: 784

Answers (1)

cjk
cjk

Reputation: 46415

A newly created workbook will always contain 3 sheets. You can programmatically remove the other 2 using their indices and the workbook object.

Upvotes: 2

Related Questions