C# VS2017 Microsoft.Office.Interop.Excel 用法

Wai Kin Sou
5 min readJun 6, 2018

簡介:Microsoft.Office.Interop.Excel 是C#用來控制Excel的套件

安裝:Visual Studio 2017可以直接在套件管理員輸入以下指令安裝(官網:https://www.nuget.org/packages/Microsoft.Office.Interop.Excel/

Install-Package Microsoft.Office.Interop.Excel

架構:有以下的Class

  1. Excel.Application:Excel應用程式,永遠只能開一個,開多個會發生錯誤
  2. Excel.Workbook:應用程式裡的活頁簿,預設情況下,不管你開幾個Excel檔案,在工作管理員裡只會出現一個Excel.exe
  3. Excel.Worksheet:活頁簿裡的工作表
  4. Excel.Range:工作表裡的儲存格,一格也是Range,多格也是Range。EG:單格:Excel.Range[“A1”]
    多格:Excel.Range[“A1:C5”]
    配合Cell來使用:Excel.Range[Excel.Worksheet.Cells[1, 1], Excel.Worksheet.Cells[5, 3]] // A1:C5
  5. Excel.Range.Cells:這是儲存格的最小單位,代表一格的Range,用法Excel.Range.Cells[1, 1]。實際上多用Range來表示Cell。

用法

#打開Excel 程式&打開工作簿

// open and load source excel file            
SrcExcelApp = new Excel.Application(); SrcExcelApp.Visible = true;
string exePath = System.Reflection.Assembly.GetEntryAssembly().Location; ExeDir = System.IO.Path.GetDirectoryName(exePath); SrcWorkBook = MainForm.SrcExcelApp.Workbooks.Open(ExeDir + "\\test.xls");

#工作表相關:

//取得工作表
Worksheet aWorkSheet = srcWorkBook.Worksheets[workSheetInd];
//新增工作薄來取得空的工作表
var destworkBook = SrcExcelApp.Workbooks.Add();

#內容相關:

// 取得使用過的區域, 如取得有值的最大列數
aWorkSheet.UsedRange; // 得到字串 "$A$1:$G$30"

#複制內容、格式、群組

// copy value and format                
Range from = oriW.Range[oriWs.Cells[3, 2],soriWs.Cells[6, 4]]; Range to = oriW.Range[oriWs.Cells[13, 2],soriWs.Cells[16, 4]];
from.Copy(); // ctrl + C
// 貼上來源格式的內容to.PasteSpecial(XlPasteType.xlPasteAllUsingSourceTheme); // ctrl + V
// 貼上相同寛度的column
to.PasteSpecial(XlPasteType.xlPasteColumnWidths);
//群組
to.Rows.Group();
from.Copy(to) //第二種寫法

#從Range中取得Range (Range.Range)

//原範圍
Range from = oriWs.Range(oriWs.Cells[3, 2],soriWs.Cells[6, 4]);
// 若想取得C4
Range to = from.Cells(3, 4);
// 若想取得C4:G10
Range to = from.Range(from.Cells(3, 4), from.Cells(7, 10))

解釋:Range.Range(cell1, optical cell2)有兩參數,第二參數為可選。

先說明只有第一個參數情況下,會從原範圍(C3:G10)中偏移了(A2到A1的向量),即row數增加1,所以會從C3得出C4。這裡的A1是絕對於worksheet的,不會隨原範圍的改變而改變。因這種情況只有一個參數,故得出的Range也是單一Cell的。

在有兩個參數的情況下,可以得出包含多個Cell的Range。新Range的右上角Cell是根據只有一個參數的情況下算出,所以在上例中,新Range也是從C4開始。

而新Range的左下角Cell是根據(E9與A2的相對向量)來作用在C4上。E8與A2相隔了4個row, 6個Column,故新Range的左下角Cell也是與C4相隔了4個row, 6個Column,即G10。

#網格顏色及格線

aRange.Interior.Color = System.Drawing.Color.MediumOrchid;Excel.Borders border = aRange.Borders;            border[XlBordersIndex.xlEdgeLeft].LineStyle = Excel.XlLineStyle.xlContinuous;            border[XlBordersIndex.xlEdgeTop].LineStyle = Excel.XlLineStyle.xlContinuous;            border[XlBordersIndex.xlEdgeBottom].LineStyle = Excel.XlLineStyle.xlContinuous;            border[XlBordersIndex.xlEdgeRight].LineStyle = Excel.XlLineStyle.xlContinuous;

--

--