C#默认创建Excel工作簿1张
问题描述:
我正在尝试使用C#COM互操作来创建一个Excel文件,但是默认情况下它会创建3个文件,而不是空白或仅一个。
需要创建它为空或只是一个:
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);
答
看看MSDN对 Workbooks.Add方法。
- 尝试
Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
或 - 查看是否可以将
xl.SheetsInNewWorkbook
属性设置为0或1。
- Try
Workbooks.Add(XlWBATemplate.xlWBATWorksheet)
, or - See if you can set the
xl.SheetsInNewWorkbook
property to 0 or 1.
$ b $我进行了验证。这是代码:
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));
}
}
}