我正在尝试使用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);
答案 0 :(得分:23)
查看MSDN对Workbooks.Add Method的解释。
Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
或xl.SheetsInNewWorkbook
属性设置为0或1。我继续进行验证。这是代码:
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));