C# Microsoft.Office 操作Excel總結


 1、導入命名空間: 

using Microsoft.Office.Interop.Excel;

 2、如何打開已有excel文檔,或者創建一個新的excel文檔 

 Application app = new Application(); Workbooks wbks = app.Workbooks; _Workbook _wbk = wbks.Add(excelTempPath + "quotaExcelTemp.xls"); Sheets shs = _wbk.Sheets; _Worksheet _wsh = (_Worksheet)shs.get_Item(1);

若打開已有excel,把“xxx”替換成該excel的文件路徑;

注:若新建一個excel文檔,“xxx”替換成true即可;不過這里新建的excel文檔默認只有一個sheet。

3、 取得、刪除和添加sheet

3.1、取得:

//i是要取得的sheet的index
_Worksheet _wsh = (_Worksheet)shs.get_Item(i)

3.2 刪除:

//刪除sheet必須的設置
app.DisplayAlerts = false;
_wsh.Delete();

3.3 添加:

//a(before),b(after):確定添加位置;c:數目;d:類型
app.Worksheets.Add(a,b,c,d);

3.4 sheet的重命名

//重命名
_wsh.Name = "xxx";

4、刪除行和列 

4.1 刪除行:

((Range)_wsh.Rows[3, Missing.Value]).Delete(XlDeleteShiftDirection.xlShiftUp);

4.2 刪除列:

//刪除列
_wsh.get_Range(
_wsh.Cells[1, 2], 
_wsh.Cells[_wsh.Rows.Count, 2]).Delete(XlDeleteShiftDirection.xlShiftToLeft
);

5、添加行和列 

5.1 添加行:

((Range)_wsh.Rows[11, Missing.Value])
.Insert(Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);

5.2 添加列:

//添加列
_wsh.get_Range(
_wsh.Cells[1, 1], _wsh.Cells[_wsh.Rows.Count, 1])
.Insert(Missing.Value, XlInsertShiftDirection.xlShiftToRight);

6、 單元格操作 

6.1 單元格的取得

//獲得單元格對象
_wsh.Cells[row, cell]

6.2 設置公式

//在對應的單元格輸入公式即可
_wsh.Cells[row, cell] = "=Sum(A1/B1)";

6.3 合並單元格

  //合並單元格
   Microsoft.Office.Interop.Excel.Range mergeRange = _wsh.Range[_wsh.Cells[19 + i, 2], _wsh.Cells[19 + i, 4]];
   //合並單元格
   mergeRange.Merge(mergeRange.MergeCells);

6.4 設置行高和列寬

((Range)_wsh.Rows[3, Missing.Value]).RowHeight = 5;
((Range)_wsh.Rows[3, Missing.Value]).ColumnWidth = 5;

6.5 設置單元格顏色 顏色共有56中,詳情請參照附錄的[顏色對照表]

((Range)_wsh.Rows[1, Missing.Value]).Interior.ColorIndex = 3;

6.6 設置字號

((Range)_wsh.Cells[1, "B"]).Font.Size = 8;

6.7 是否設置粗體

((Range)_wsh.Rows[1, Missing.Value]).Font.Bold = false;

6.8 單元格/區域、水平垂直居中

((Range)_wsh.Cells[2, 1]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
//靠左
((Range)_wsh.Cells[15, 7]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
//靠右
 ((Range)_wsh.Cells[30, 8]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;

6.9 設置區域邊框

((Range)_wsh.Cells[3, 3]).Borders.LineStyle = 3;

6.10 設置邊框的上、下、左、右線條

//
_wsh.get_Range(
_wsh.Cells[2, 1], _wsh.Cells[2, 2])
.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//
 
//
_wsh.get_Range(
_wsh.Cells[2, 1], _wsh.Cells[2, 2])
.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//
 
//
_wsh.get_Range(
_wsh.Cells[2, 1], _wsh.Cells[2, 2])
.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;////
_wsh.get_Range(
_wsh.Cells[2, 1], _wsh.Cells[2, 2])
.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;

7、指定區域的復制 

_Worksheet _wsh = (_Worksheet)shs.get_Item(1);//復制選中區域的內容
 
Range range = _wsh.get_Range(_wsh.Cells[7, 1], _wsh.Cells[10, _wsh.Columns.Count]);
 
range.Select();
range.Copy(Type.Missing);
 
//選中粘貼的起始位置
Range test = ((Range)_wsh.Cells[11, 1]);
test.Select();
 
//屏蔽掉Alert,默認確定粘貼
app.DisplayAlerts = false;
test.Parse(Missing.Value, Missing.Value);

注:Type.Missing和Missing.Value,在excel的操作中被視為某些參數的默認值,他們起到的作用很多時候是形式補足參數

8、excel文件的保存,及后續處理 

8.1 文件保存

//屏蔽掉系統跳出的Alert
app.AlertBeforeOverwriting = false;
 
//保存到指定目錄
SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

 

注:這個地方只能采用該方法保存,不然在指定路徑下保存文件外,在我的文檔中也會生成一個對應的副本

8.2 后續處理:退出和釋放

//退出
app.Quit();
 
//釋放掉多余的excel進程
System.Runtime.InteropServices.Marshal.ReleaseComObject(app); 

說明:在application關閉的過程中,通常我們有兩種方案:

#直接退出app

#先關閉workbook,然后關閉workbooks,最后在退出app

鑒於這兩種方式,或許本質上是一樣的(這點需要證明),但是依據我們軟件開發的原則:哪里需要哪里聲明,哪里結束哪里釋放回收。

既然在直接退出app的時候,我們不清楚workbook和workbooks具體在什么時間關閉,不如在結束的時候直接手動關閉,這樣做可以做到資源的快速直接回收;

所以,建議采用先關閉workbook,然后關閉workbooks,最后在退出app。

9、關於單元格設置域和取得域里需要的數據 

9.1 若單元格已經設置為下拉框

//這里的“1,2,3”設置的就是下拉框的值
((Range)_wsh.Cells[2, 1])
.Validation.Modify(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing, "1,2,3", Type.Missing);

9.2 若單元格還沒有設置為下拉框的形式

 

((Range)_wsh.Cells[2, 1])
.Validation.Add(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing,"1,2,3", Type.Missing);

9.3 取得下拉框域的值

string strValue = ((Range)_wsh.Cells[2, 1]).Validation.Formula1;

注:若在excel模板中通過有效性設定了下拉框的值,strValue得到的將會是excel里的公式,需將其轉換, 取得strValue后,可以根據其索引得到你需要的數值;

 

10、 隱藏行和隱藏列 

10.1 隱藏行

_wsh.get_Range(_wsh.Cells[19, 1], _wsh.Cells[22, 1]).EntireRow.Hidden = true;

10.2 隱藏列

_wsh.get_Range(_wsh.Cells[1, 1], _wsh.Cells[_wsh.Rows.Count, 1])
.EntireColumn.Hidden = true;

11、案例

  private string SaveExcel(PrintQuotationOrderViewModel model)
        {
            if (model == null) return string.Empty;
            string excelTempPath = Server.MapPath("/Resources/Temp/");
            if (!Directory.Exists(excelTempPath))
            {
                Directory.CreateDirectory(excelTempPath);
            }
            Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            Workbooks wbks = app.Workbooks;
            _Workbook _wbk = wbks.Add(excelTempPath + "quotaExcelTemp.xls");
            Sheets shs = _wbk.Sheets;
            _Worksheet _wsh = (_Worksheet)shs.get_Item(1);
            //設置客戶單號
            _wsh.Cells[7, 8] = model.QuotationOrder.CustomerPurchaseNumber;
            ((Range)_wsh.Cells[7, 8]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            //設置報價單號
            _wsh.Cells[8, 8] = model.QuotationOrder.Number;
            ((Range)_wsh.Cells[8, 8]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;


            //設置報價日期
            _wsh.Cells[9, 8] = model.QuotationOrder.QuotedOn.ToString("yyyy-MM-dd");
            ((Range)_wsh.Cells[9, 8]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            //設置銷售人員
            _wsh.Cells[10, 8] = model.QuotationOrder.SalesmanName;
            //設置客戶公司
            _wsh.Cells[12, 3] = model.QuotationOrder.Buyer.Company.Name;
            //設置客戶部門
            _wsh.Cells[13, 3] = model.QuotationOrder.Buyer.Department;
            //設置聯系人
            _wsh.Cells[13, 7] = model.QuotationOrder.Buyer.Name;
            //設置收貨公司
            _wsh.Cells[14, 3] = model.QuotationOrder.Receiver.Company;
            //設置收貨部門
            _wsh.Cells[14, 7] = model.QuotationOrder.Receiver.Department;
            //設置收貨人
            _wsh.Cells[15, 3] = model.QuotationOrder.Receiver.Name;
            //設置聯系電話
            _wsh.Cells[15, 7] = model.QuotationOrder.Receiver.Mobile;
            ((Range)_wsh.Cells[15, 7]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
            //設置收貨地址
            _wsh.Cells[16, 3] = model.QuotationOrder.Receiver.Address;

            int count = model.QuotationItems.Count;
            for (int i = 0; i < count; i++)
            {
                ((Range)_wsh.Rows[19 + i, System.Reflection.Missing.Value]).Insert(System.Reflection.Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);


                _wsh.Cells[19 + i, 1] = (i+1).ToString(); //第一項 設置編號
                _wsh.Cells[19 + i, 2] = $"{model.QuotationItems[i].CustomCode}\r\n{model.QuotationItems[i].Product.Code}\r\n{model.QuotationItems[i].Product.Name}"; //第二項 設置 客戶零件號/模號/料號 產品型號 產品名稱


                //合並單元格
                Microsoft.Office.Interop.Excel.Range mergeRange = _wsh.Range[_wsh.Cells[19 + i, 2], _wsh.Cells[19 + i, 4]];
                //合並單元格
                mergeRange.Merge(mergeRange.MergeCells);
                //((Range)_wsh.Rows[19 + i, System.Reflection.Missing.Value]).Merge(mergeRange.MergeCells);

                _wsh.Cells[19 + i, 5] = model.QuotationItems[i].Quantity; //第三項 設置數量
                _wsh.Cells[19 + i, 6] = model.QuotationItems[i].Quotation.UnitPriceWithTax >=0 ? ((decimal)model.QuotationItems[i].Quotation.UnitPriceWithTax).ToString("f2") : ""; //第四項 設置含稅單價(元) 
                _wsh.Cells[19 + i, 7] = model.QuotationItems[i].Quotation.SubtotalWithTax; //第五項 設置小計(元)
                _wsh.Cells[19 + i, 8] = model.QuotationItems[i].Quotation.DispatchDays>=0 ? ((int)model.QuotationItems[i].Quotation.DispatchDays).ToString() : ""; //第六項 設置發貨天數(工作日)
                _wsh.Cells[19 + i, 9] = model.QuotationItems[i].Remark; //第七項 設置備注

                ((Range)_wsh.Rows[19 + i, System.Reflection.Missing.Value]).RowHeight = 45;
            }

            //設置結算方式
            _wsh.Cells[24 + count, 3] = model.Payment;
            //設置產品未稅總價
            _wsh.Cells[23 + count, 8] = model.QuotationOrder.TotalWithoutTax.ToString("f2");
            //設置優惠金額0.00
            _wsh.Cells[24 + count, 8] = model.QuotationOrder.Preferential != null ? model.QuotationOrder.Preferential.Discount.HasValue ? ((decimal)model.QuotationOrder.Preferential.Discount).ToString("f2") : "0.00" : "0.00";
            //設置運費
            _wsh.Cells[25 + count, 8] = model.QuotationOrder.Shipping.Amount.ToString("f2");
            //設置運費折扣
            _wsh.Cells[26 + count, 8] = model.QuotationOrder.Shipping.Discount.ToString("f2");
            //設置增值稅
            _wsh.Cells[27 + count, 8] = model.QuotationOrder.Tax.ToString("f2");
            //設置含稅總金額(小寫)
            _wsh.Cells[29 + count, 8] = model.QuotationOrder.TotalWithTax.ToString("f2");
            //設置含稅總金額(大寫)
            _wsh.Cells[30 + count, 8] = model.QuotationOrder.TotalWithTaxInChinese;
            ((Range)_wsh.Cells[30 + count, 8]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignRight;

            app.DisplayAlerts = false;
            app.AlertBeforeOverwriting = false;
            excelTempPath = Server.MapPath("/Resources/Excel/");
            if (!Directory.Exists(excelTempPath))
            {
                Directory.CreateDirectory(excelTempPath);
            }
            string savePath = excelTempPath + DateTime.Now.ToFileTime() + ".xls";
            _wbk.SaveCopyAs(savePath);
            wbks.Close();
            app.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
            return savePath;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM