2015-06-11 41 views
1

我只将数据写入1个Excel工作表,但我想创建一个新工作表并将其命名为“xxx”并在其中写入数据。创建一个新的Excel工作表并将其命名

这是我现在有:

private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel; 
private static Workbook newWorkbook_First = null; 
private static _Worksheet objsheet = null; 

excel_init("C:\\Users\\me\\Desktop\\excel2.xlsx"); 

for (int i = 1; i < WindowsXPLijst.Count; i++) 
{ 
    excel_setValue("B" + i, WindowsXPLijst[i]); 
} 

excel_close(); 

static void excel_init(String path) 
{ 
    appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 

    if (System.IO.File.Exists(path)) 
    { 
     // then go and load this into excel 
     newWorkbook_First = appExcel.Workbooks.Open(path, true, true); 
     objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet; 
    } 
    else 
    { 
     try 
     { 
      appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
      appExcel.Visible = true; 
      newWorkbook_First = appExcel.Workbooks.Add(1); 
      objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook_First.Sheets[1]; 
     } 
     catch (Exception e) 
     { 
      Console.Write("Error"); 
     } 
     finally 
     { 
     } 
    } 

} 

static void excel_setValue(string cellname, string value) 
{ 
    objsheet.get_Range(cellname).set_Value(Type.Missing, value); 
    objsheet.get_Range(cellname).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); 
} 

我没有那么多变化,但因为我不知道如何改变这一功能:

static void excel_setValue(string cellname, string value, string tab) 
{ 
    objsheet = tab // No ica what to exactly put here 
} 

{ 
    excel_setValue("B" + i, WindowsXPLijst[i], "xxx"); 
} 

回答

2

这将创建一个您的最后一张纸后,新的工作表:

Dim WS As Worksheet 
Set WS =Sheets.Add(After:=Sheets(Worksheets.count)) 
WS.name = "xxx" 

此代码是代码的精简版发现here

+0

愚蠢的问题:它找不到类型或命名空间Dim。如何解决这个问题? – wouter

+2

这个答案是用VBA编写的,而你正在寻找一个C#答案。从问题中删除[tag:vba]标签可能是有意义的,@wouter – FreeMan

+0

我不明白为什么当我回复VBA标签时我被低估了 – Paradox

相关问题