c_操作excel总结

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C#操作Excel总结

Excel 基本操作

查看Excel中宏的方法如下:

ALT+F11

0. 导入命名空间:

view source

print?

1 using Microsoft.Office.Core;

2 using Microsoft.Office.Interop.Excel;

3 using System.IO;

4 using System.Reflection;

1. 如何打开已有excel文档,或者创建一个新的excel文档

view source

print?

1 Application app = new Application();

2 Workbooks wbks = app.Workbooks;

3 _Workbook _wbk = wbks.Add(xxx);

若打开已有excel,把“xxx”替换成该excel的文件路径;

注:若新建一个excel文档,“xxx”替换成true即可;不过这里新建的excel文档默认只有一个sheet。

2. 取得、删除和添加sheet

view source

print?

1 Sheets shs = _wbk.Sheets;

2.1取得:

view source

print?

1 //i 是要取得的sheet 的index

2 _Worksheet _wsh = (_Worksheet)shs.get_Item(i)

2.2 删除: view source

print?

1 //删除sheet 必须的设置

2 app.DisplayAlerts = false;

3 _wsh.Delete();

2.3 添加: view source

print?

1 //a(before),b(after):确定添加位置;c :数目;d :类型

2 app.Worksheets.Add(a ,b ,c ,d);

2.4 sheet 的重命名 view source

print?

1 _ = "xxx";

3. 删除行和列

3.1 删除行: view source

print?

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

3.2 删除列: view source

print?

1 _wsh.get_Range(

2 _wsh.Cells[1, 2],

3 _wsh.Cells[_wsh.Rows.Count, 2]).Delete(XlDeleteShiftDirection.xlShiftToLeft

4 );

4. 添加行和列

4.1 添加行:

view source

print?

1 ((Range)_wsh.Rows[11, Missing.Value])

2 .Insert(Missing.Value, XlInsertFormatOrigin.xlFormatFromLeftOrAbove);

4.2 添加列:

view source

print?

1 _wsh.get_Range(

2 _wsh.Cells[1, 1], _wsh.Cells[_wsh.Rows.Count, 1])

3 .Insert(Missing.Value, XlInsertShiftDirection.xlShiftToRight);

5. 单元格操作

5.1 单元格的取得

view source

print?

1 //获得单元格对象

2 _wsh.Cells[row, cell]

5.2 设置公式

view source

print?

1 //在对应的单元格输入公式即可

2 _wsh.Cells[row, cell] = "=Sum(A1/B1)";

5.3 合并单元格

view source

print?

1 ((Range)_wsh.Rows[1, Missing.Value]).Merge(Missing.Value);

5.4 设置行高和列宽

view source

print?

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

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

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

view source

print?

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

5.6 设置字号

view source

print?

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

5.7 是否设置粗体

view source

print?

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

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

view source

print?

1 ((Range)_wsh.Cells[2, 1]).HorizontalAlignment = XlVAlign.xlVAlignCenter;

5.9 设置区域边框

view source

print?

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

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

view source

print?

01 //左

02 _wsh.get_Range(

相关文档
最新文档