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();

若打开已有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[, Missing.Value]).Delete(XlDeleteShiftDirection.xlShiftUp);

4.2 删除列:

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

5、添加行和列 

5.1 添加行:

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

5.2 添加列:

//添加列
_wsh.get_Range(
_wsh.Cells[, ], _wsh.Cells[_wsh.Rows.Count, ])
.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[ + i, ], _wsh.Cells[ + i, ]];
//合并单元格
mergeRange.Merge(mergeRange.MergeCells);

6.4 设置行高和列宽

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

6.5 设置单元格颜色 颜色共有56中,详情请参照附录的[颜色对照表]

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

6.6 设置字号

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

6.7 是否设置粗体

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

6.8 单元格/区域、水平垂直居中

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

6.9 设置区域边框

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

6.10 设置边框的上、下、左、右线条

//左
_wsh.get_Range(
_wsh.Cells[, ], _wsh.Cells[, ])
.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;// //右
_wsh.get_Range(
_wsh.Cells[, ], _wsh.Cells[, ])
.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;// //上
_wsh.get_Range(
_wsh.Cells[, ], _wsh.Cells[, ])
.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//下 //下
_wsh.get_Range(
_wsh.Cells[, ], _wsh.Cells[, ])
.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;

7、指定区域的复制 

_Worksheet _wsh = (_Worksheet)shs.get_Item();//复制选中区域的内容

Range range = _wsh.get_Range(_wsh.Cells[, ], _wsh.Cells[, _wsh.Columns.Count]);

range.Select();
range.Copy(Type.Missing); //选中粘贴的起始位置
Range test = ((Range)_wsh.Cells[, ]);
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[, ])
.Validation.Modify(XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertStop, Type.Missing, "1,2,3", Type.Missing);

9.2 若单元格还没有设置为下拉框的形式

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

9.3 取得下拉框域的值

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

注:若在excel模板中通过有效性设定了下拉框的值,strValue得到的将会是excel里的公式,需将其转换, 取得strValue后,可以根据其索引得到你需要的数值;

10、 隐藏行和隐藏列 

10.1 隐藏行

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

10.2 隐藏列

_wsh.get_Range(_wsh.Cells[, ], _wsh.Cells[_wsh.Rows.Count, ])
.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();
//设置客户单号
_wsh.Cells[, ] = model.QuotationOrder.CustomerPurchaseNumber;
((Range)_wsh.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
//设置报价单号
_wsh.Cells[, ] = model.QuotationOrder.Number;
((Range)_wsh.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //设置报价日期
_wsh.Cells[, ] = model.QuotationOrder.QuotedOn.ToString("yyyy-MM-dd");
((Range)_wsh.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
//设置销售人员
_wsh.Cells[, ] = model.QuotationOrder.SalesmanName;
//设置客户公司
_wsh.Cells[, ] = model.QuotationOrder.Buyer.Company.Name;
//设置客户部门
_wsh.Cells[, ] = model.QuotationOrder.Buyer.Department;
//设置联系人
_wsh.Cells[, ] = model.QuotationOrder.Buyer.Name;
//设置收货公司
_wsh.Cells[, ] = model.QuotationOrder.Receiver.Company;
//设置收货部门
_wsh.Cells[, ] = model.QuotationOrder.Receiver.Department;
//设置收货人
_wsh.Cells[, ] = model.QuotationOrder.Receiver.Name;
//设置联系电话
_wsh.Cells[, ] = model.QuotationOrder.Receiver.Mobile;
((Range)_wsh.Cells[, ]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;
//设置收货地址
_wsh.Cells[, ] = model.QuotationOrder.Receiver.Address; int count = model.QuotationItems.Count;
for (int i = ; i < count; i++)
{
((Range)_wsh.Rows[ + i, System.Reflection.Missing.Value]).Insert(System.Reflection.Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove); _wsh.Cells[ + i, ] = (i+).ToString(); //第一项 设置编号
_wsh.Cells[ + i, ] = $"{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[ + i, ], _wsh.Cells[ + i, ]];
//合并单元格
mergeRange.Merge(mergeRange.MergeCells);
//((Range)_wsh.Rows[19 + i, System.Reflection.Missing.Value]).Merge(mergeRange.MergeCells); _wsh.Cells[ + i, ] = model.QuotationItems[i].Quantity; //第三项 设置数量
_wsh.Cells[ + i, ] = model.QuotationItems[i].Quotation.UnitPriceWithTax >= ? ((decimal)model.QuotationItems[i].Quotation.UnitPriceWithTax).ToString("f2") : ""; //第四项 设置含税单价(元)
_wsh.Cells[ + i, ] = model.QuotationItems[i].Quotation.SubtotalWithTax; //第五项 设置小计(元)
_wsh.Cells[ + i, ] = model.QuotationItems[i].Quotation.DispatchDays>= ? ((int)model.QuotationItems[i].Quotation.DispatchDays).ToString() : ""; //第六项 设置发货天数(工作日)
_wsh.Cells[ + i, ] = model.QuotationItems[i].Remark; //第七项 设置备注 ((Range)_wsh.Rows[ + i, System.Reflection.Missing.Value]).RowHeight = ;
} //设置结算方式
_wsh.Cells[ + count, ] = model.Payment;
//设置产品未税总价
_wsh.Cells[ + count, ] = model.QuotationOrder.TotalWithoutTax.ToString("f2");
//设置优惠金额0.00
_wsh.Cells[ + count, ] = model.QuotationOrder.Preferential != null ? model.QuotationOrder.Preferential.Discount.HasValue ? ((decimal)model.QuotationOrder.Preferential.Discount).ToString("f2") : "0.00" : "0.00";
//设置运费
_wsh.Cells[ + count, ] = model.QuotationOrder.Shipping.Amount.ToString("f2");
//设置运费折扣
_wsh.Cells[ + count, ] = model.QuotationOrder.Shipping.Discount.ToString("f2");
//设置增值税
_wsh.Cells[ + count, ] = model.QuotationOrder.Tax.ToString("f2");
//设置含税总金额(小写)
_wsh.Cells[ + count, ] = model.QuotationOrder.TotalWithTax.ToString("f2");
//设置含税总金额(大写)
_wsh.Cells[ + count, ] = model.QuotationOrder.TotalWithTaxInChinese;
((Range)_wsh.Cells[ + count, ]).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;
}

C# Microsoft.Office 操作Excel总结的更多相关文章

  1. Excel操作 Microsoft.Office.Interop.Excel.dll的使用

    ----转载: http://www.cnblogs.com/lanjun/archive/2012/06/17/2552920.html 先说说题外话,前段时间近一个月,我一直在做单据导入功能,其中 ...

  2. C# 使用自带Microsoft.Office.Interop.Excel简单操作Excel文件

    项目添加应用 Microsoft.Office.Interop.Excel.dll 文件 引用命名空间: using Excel = Microsoft.Office.Interop.Excel; 简 ...

  3. Microsoft.Office.Interop.Excel操作Excel文件时出现的问题及解决方案

    问题描述: Microsoft.Office.Interop.Excel.Worksheet 打不开文件 Microsoft Office Excel 不能访问文件"a.xls". ...

  4. 基于C#语言利用Microsoft.office.introp.excel操作Excel总结

    终于解决了质量评估测试软件在任意装有excel(2010以下版本)的电脑上正常使用的问题!!!!!!!!!! 可到http://www.microsoft.com/en-sa/download/con ...

  5. c#操作excel方式三:使用Microsoft.Office.Interop.Excel.dll读取Excel文件

    1.引用Microsoft.Office.Interop.Excel.dll 2.引用命名空间.使用别名 using System.Reflection; using Excel = Microsof ...

  6. Microsoft.Office.Interop.Excel Find 操作

    public void SearchLoactions(string filepath, int start, int end ,string expectvalue) { if (end >= ...

  7. Microsoft.Office.Interop.Excel的用法以及利用Microsoft.Office.Interop.Excel将web页面转成PDF

    1.常见用法           using Microsoft.Office.Interop.Excel; 1)新建一个Excel ApplicationClass ExcelApp = New A ...

  8. 引用Microsoft.Office.Interop.Excel出现的问题

    引用Microsoft.Office.Interop.Excel出现的问题   转自:http://www.hccar.com/Content,2008,6,11,75.aspx,作者:方继祥 操作背 ...

  9. “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用

    “DataTable”是“System.Data.DataTable”和“Microsoft.Office.Interop.Excel.DataTable”之间的不明确的引用 造成这个错误的原因是,在 ...

随机推荐

  1. Python面向对象编程核心思想

    原文地址https://blog.csdn.net/weixin_42134789/article/details/80194788 https://blog.csdn.net/happyjxt/ar ...

  2. TCP的拥塞窗口和快速恢复机制的一些备忘及一点想法

    rwnd(窗口,代表接收端的处理能力).cwnd(拥塞窗口,从发送端看当前网络整体承载能力).ssthresh(快速增长切换成慢速增长的界限值) 1.慢启动,是指数增长(对面确认多少个包,就增加多少) ...

  3. openresty开发系列39--nginx+lua实现接口签名安全认证

    一)需求背景现在app客户端请求后台服务是非常常用的请求方式,在我们写开放api接口时如何保证数据的安全,我们先看看有哪些安全性的问题 请求来源(身份)是否合法?请求参数被篡改?请求的唯一性(不可复制 ...

  4. php中heredoc与nowdoc的使用方法、定界符<<<的使用方法

    一.heredoc结构及用法 Heredoc 结构就象是没有使用双引号的双引号字符串,这就是说在 heredoc 结构中单引号不用被转义.其结构中的变量将被替换,但在 heredoc 结构中含有复杂的 ...

  5. JMeter 使用 http长连接的方法

    前言 如果需要在JMeter通过http长连接发送请求,首先需要选择了Use KeepAlive 长连接协议,虽然默认是勾选的,但也需要确认一下. 除了选择了Use KeepAlive 长连接协议,还 ...

  6. springboot使用SpringTask实现定时任务

    SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用. 只需要在配置类中添加一个@EnableScheduling注解即可开启S ...

  7. 【电商日志项目之五】数据分析-MR方式

    环境 hadoop-2.6.5 hbase-0.98.12.1-hadoop2 新增用户指标分析(1)用户分析模块 (2)浏览器分析模块 根据分析效果图,找出分析的维度:用户分析是指某个时间段内的数量 ...

  8. mysql执行计划详解,

    一.语法 explain SQL语句 例如: explain ; 二.explain输出解释 +----+-------------+-------+-------+----------------- ...

  9. python sys模块(12)

    在python sys模块提供对解释器使用或维护的一些变量的访问,以及与解释器强烈交互的函数!关于sys模块在官网也有详细的介绍:python sys模块官方介绍. 一.sys模块简介 sys.arg ...

  10. 05 Mybatis的CRUD操作和Mybatis连接池

    1.CRUD的含义 CRUD是指在做计算处理时的增加(Create).读取(Retrieve)(重新得到数据).更新(Update)和删除(Delete)几个单词的首字母简写.主要被用在描述软件系统中 ...