创建一个新的Excel工作表并命名它

时间:2015-06-11 20:20:57

标签: c# excel

我只将我的数据写入1张Excel表格,但我想制作一张新表格并将其称为" xxx"并在其中写入数据。

以下是我现在所拥有的:

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");
}

1 个答案:

答案 0 :(得分:2)

这会在最后一张纸张后创建一张新纸张:

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

此代码是找到的代码here

的精简版本