C#默认情况下,使用1张创建Excel工作簿

时间:2011-11-09 14:06:07

标签: c# excel office-interop

我正在尝试使用C#COM互操作创建一个Excel文件,但它似乎默认创建了3张而不是空或只有一张。 创建它需要什么空或只需一个:

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

2 个答案:

答案 0 :(得分:23)

查看MSDN对Workbooks.Add Method的解释。

  1. 尝试Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
  2. 查看是否可以将xl.SheetsInNewWorkbook属性设置为0或1。
  3. 我继续进行验证。这是代码:

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

答案 1 :(得分:2)

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

xl = new Excel.Application();
xl.SheetsInNewWorkbook = 1;
xl.Visible = true;

wb = (_Workbook)(xl.Workbooks.Add(Missing.Value));