创建Excel工作簿,默认为1个工作表
本文关键字:1个 工作 默认 Excel 工作簿 创建 | 更新日期: 2023-09-27 18:14:10
我试图用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);
看看MSDN对workbook的解释。添加方法。
- 尝试
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));
}
}
}
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));