Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Create Excel workbook with 1 sheet by default

I'm trying to create an Excel file with C# COM interop but seems it create it by default with 3 sheets instead of empty or only one. What is needed to create it Empty or just with one:

Excel.Application xl = null;
Excel._Workbook wb = null;

// Create a new instance of Excel from scratch
xl = new Excel.Application();
xl.Visible = true;     
wb = (Excel._Workbook)(xl.Workbooks.Add(Missing.Value));

wb.SaveAs(@"C:\a.xls", Excel.XlFileFormat.xlWorkbookNormal,
 null, null, false, false, Excel.XlSaveAsAccessMode.xlShared,
 false, false, null, null, null);
like image 588
Moti Avatar asked Nov 09 '11 14:11

Moti


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.


1 Answers

Take a look at MSDN's explanation of Workbooks.Add Method.

  1. Try Workbooks.Add(XlWBATemplate.xlWBATWorksheet), or
  2. See if you can set the xl.SheetsInNewWorkbook property to 0 or 1.

I went ahead and verified this. Here is the code:

using Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Application xl = null;
            _Workbook wb = null;

            // Option 1
            xl = new Application();
            xl.Visible = true;
            wb = (_Workbook)(xl.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));

            // Option 2
            xl = new Application();
            xl.SheetsInNewWorkbook = 1;
            xl.Visible = true;
            wb = (_Workbook)(xl.Workbooks.Add(Missing.Value));

        }
    }
}
like image 101
Matt Avatar answered Sep 16 '22 18:09

Matt