2017-11-18 52 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); 
} 

另外,您可以遍歷工作簿中的每個樣式,但是您調用它的次數越多,樣式越多效率越低。

延遲加載方法的另一個優點是如果您實現多個樣式,則可以將其作爲附加參數傳遞。