報表開發中常需美化儲存格外觀,如設定邊框線條樣式、粗細、顏色,以及填充圖案與顏色。本文透過 C# 操作 Excel COM 物件,示範如何對指定範圍(G4:H5)套用自訂樣式:填充十字交叉圖案、設定外框與內部邊框、指定左邊框為紅色虛線。
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(@"Z:\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
app.DisplayAlerts = false;
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.get_Item(1);
Excel.Range rng = ws.get_Range("G4", "H5");
rng.Value = "123";
// 建立自訂樣式(可選,此處直接操作 Range 屬性)
// Excel.Style style = wb.Styles.Add("CustomBorder", Type.Missing);
// 設定填充圖案:十字交叉
rng.Interior.Pattern = Excel.XlPattern.xlPatternCrissCross;
// 設定邊框粗細
rng.Borders.Weight = 2; // xlMedium
// 逐邊設定線條樣式
rng.Borders.get_Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous;
rng.Borders.get_Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous;
rng.Borders.get_Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous;
rng.Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlDot; // 虛線
rng.Borders.get_Item(Excel.XlBordersIndex.xlEdgeLeft).Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red); // 紅色
// 關閉不需要的對角線與內部格線
rng.Borders.get_Item(Excel.XlBordersIndex.xlDiagonalDown).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
rng.Borders.get_Item(Excel.XlBordersIndex.xlDiagonalUp).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
rng.Borders.get_Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
rng.Borders.get_Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
wb.SaveAs(@"Z:\Book2.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// ... 釋放資源 ...
| 屬性/方法 | 用途 |
|---|---|
Interior.Pattern | 設定填充圖案,如 xlPatternCrissCross(十字)、xlPatternSolid(實心)等。 |
Borders.Weight | 設定邊框粗細:xlHairline、xlThin、xlMedium、xlThick。 |
Borders[Index].LineStyle | 指定各邊框線條:xlContinuous(實線)、xlDot(虛線)、xlDash(破折線)等。 |
Borders[Index].Color | 設定邊框顏色,需透過 ColorTranslator.ToOle 轉換 .NET Color 結構。 |
Style 物件,再指派 Range.Style,效能更佳。XlBordersIndex 包含:xlEdgeTop/Bottom/Left/Right、xlInsideHorizontal/Vertical、xlDiagonalDown/Up。掌握這些細節,即可在 C# 中精準控制 Excel 報表的視覺呈現,產出專業級文件。