2017-11-18 150 views
0

这工作正常,直到我将它添加到一个循环中。我认为这是因为我添加了两次样式。Excel.Style:样式类的添加方法失败

我想添加样式到工作表的第一行。

if (LastRowInsertionIndex==1) 
{ 
    xlWorkSheet.Activate(); 
    xlWorkSheet.Cells[1, 1] = "CaseNumber"; 
    xlWorkSheet.Cells[1, 2] = "Names"; 
    xlWorkSheet.Cells[1, 3] = "Bar Number"; 
    xlWorkSheet.Cells[1, 4] = "Email"; 
    xlWorkSheet.Cells[1, 5] = "Title"; 

    Excel.Style style = WorkBook.Styles.Add("NewStyle"); 

    //style.Font.Name = "Verdana"; 
    style.Font.Size = 14; 
    style.Font.Bold = true; 
    xlWorkSheet.Cells[1, 1].Style = style; 
} 

Excel.Style style = WorkBook.Styles.Add("NewStyle");导致错误;

Add method of Styles class failed 

而我必须在第一列中选​​择每个单元格1。有没有办法选择所有行。

回答

0

由于Workbook.Styles没有出现有一个索引,你可以实现这样的延迟加载的方法:

private Dictionary<Excel.Workbook, Excel.Style> _MyStyle = 
    new Dictionary<Excel.Workbook, Excel.Style>(); 
private Excel.Style MyStyle(Excel.Workbook Wb) 
{ 
    Excel.Style myStyle; 
    if (!_MyStyle.TryGetValue(Wb, out myStyle)) 
    { 
     myStyle = Wb.Styles.Add("NewStyle"); 

     myStyle.Font.Name = "Verdana"; 
     myStyle.Font.Size = 14; 
     myStyle.Font.Bold = true; 
     _MyStyle.Add(Wb, myStyle); 
    } 

    return myStyle; 
} 

,然后实现它是这样的:

if (LastRowInsertionIndex == 1) 
{ 
    xlWorkSheet.Activate(); 
    xlWorkSheet.Cells[1, 1] = "CaseNumber"; 
    xlWorkSheet.Cells[1, 2] = "Names"; 
    xlWorkSheet.Cells[1, 3] = "Bar Number"; 
    xlWorkSheet.Cells[1, 4] = "Email"; 
    xlWorkSheet.Cells[1, 5] = "Title"; 

    xlWorkSheet.Cells[1, 1].Style = MyStyle(Workbook); 
} 

另外,您可以遍历工作簿中的每个样式,但是您调用它的次数越多,样式越多效率越低。

延迟加载方法的另一个优点是如果您实现多个样式,则可以将其作为附加参数传递。