2015-06-11 67 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

相關問題