C# Create Excel workbook with 1 sheet by default

前端 未结 2 1596
醉梦人生
醉梦人生 2021-02-19 18:13

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

2条回答
  •  死守一世寂寞
    2021-02-19 19:10

    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));
    
            }
        }
    }
    

提交回复
热议问题