如何使用c#动态更改工作表对象

时间:2014-06-23 08:31:13

标签: c# excel-interop

这是我的示例代码

    Worksheet ws= (Worksheet)wb.Worksheets[1];

     Excel.Worksheet ws2 = wb.Sheets.Add(missing, missing, 1, missing)
                    as Excel.Worksheet;


    ws.get_Range("A1", "K2").Merge(true);
    ws.get_Range("A1", "K2").Font.Name = "Times New Roman";
    ws.get_Range("A1", "K2").Font.Size = "14";
    ws.get_Range("A1", "K2").Font.Bold = true;
    ws.get_Range("A1", "K2").FillLeft();
    ws.Cells[2, 1] = "Line Chart Summary-BOTTOM";

above i using ws as object name .i want to change ws to ws1 using C# coding.


    ws1.get_Range("A1", "K2").Merge(true);
    ws1.get_Range("A1", "K2").Font.Name = "Times New Roman";
    ws1.get_Range("A1", "K2").Font.Size = "14";
    ws1.get_Range("A1", "K2").Font.Bold = true;
    ws1.get_Range("A1", "K2").FillLeft();
    ws1.Cells[2, 1] = "Line Chart Summary-BOTTOM"; Like this i want to change.

在.NET 3.5中使用C#与Visual Studio 2008,我试图在打开的工作簿中设置焦点(或激活)特定工作表:对于一个用户我使用ws另一个用户我使用ws1所以我想动态地更改工作表对象。

谢谢你提前

1 个答案:

答案 0 :(得分:0)

听起来您想要引用不同用户的不同工作表。

Worksheet wsTemp = null;

try
{    
    if (user == "A")
        wsTemp = ws1;
    else
        wsTemp = ws2;

    wsTemp .get_Range("A1", "K2").Merge(true);
    wsTemp .get_Range("A1", "K2").Font.Name = "Times New Roman";
    wsTemp .get_Range("A1", "K2").Font.Size = "14";
    wsTemp .get_Range("A1", "K2").Font.Bold = true;
    wsTemp .get_Range("A1", "K2").FillLeft();
    wsTemp .Cells[2, 1] = "Line Chart Summary-BOTTOM";

}
finally
{
    // release com object here
}