使用4个工作表创建工作簿&名称

时间:2014-04-15 12:30:39

标签: c# vsto

我需要创建一个新的Excel工作簿,其中包含4个工作表和每个工作表的自定义名称。我试过这个但是在添加第一张表后它给了我一个COMEXception

docExcel = new Microsoft.Office.Interop.Excel.Application();
docExcel.Visible = true;
docExcel.DisplayAlerts = false;
_Workbook workbooksExel = docExcel.ActiveWorkbook;
workbooksExcel = (_Workbook)(docExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet));
Worksheet worksheet = (Worksheet)docExcel.Worksheets["Sheet 1"];
worksheet.Name = "WS 1";
Worksheet worksheet1 = (Worksheet)docExcel.Worksheets["Sheet 2"];
workhseet1.Name = "WS 2";
Worksheet worksheet2 = (Worksheet)docExcel.Worksheets["Sheet 3"];
worksheet2.Name = "WS 3";
Worksheet worksheet3 = (Worksheet)docExcel.Worksheets["Sheet 4"];
worksheet3.Name = "WS 4";

1 个答案:

答案 0 :(得分:0)

试试这个 - 这是我用来做同样的事情

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = ap.WOrkbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
Sheets xlSheets = null
Worksheet xlNewSheet = null;
xlSheets = workbook.Sheets as Sheets;
app.Visible = true;
//And you can do this as many times as the sheets you want to add
worksheet = workbook.Worksheets[1];
worksheet.Name = "Sheet 1";
worksheet = workbook.Worksheets[2];
worksheet.Name = "Sheet 2";