excel进程相关
打开一个excel的进程
using Excel = Microsoft.Office.Interop.Excel;
using Application = Microsoft.Office.Interop.Excel.Application;
//创建一个excel的进程。什么都没有,没有sheet
Application app = new Excel.Application();
//让打开的excel可见
app.Visible = true;
判断是否有excel进程
using System.Diagnostics;
/// <summary>
/// 判断是否有excel进程
/// </summary>
/// <returns></returns>
public Boolean isHavingExcelProcess()
{
Process[] ps = Process.GetProcessesByName("EXCEL");
return ps.Length == 0 ? false : true;
}
得到当前的excel文件指定单元格的内容
using System.Runtime.InteropServices;
private void button4_Click(object sender, EventArgs e)
{
//得到当前打开的excel文件对象
Application excelApp = Marshal.GetActiveObject("EXCEL.Application") as Excel.Application;
//得到当前的sheet对象
Excel.Worksheet sheet = excelApp.ActiveSheet as Excel.Worksheet;
//得到指定的单元格的内容
MessageBox.Show(sheet.Range["C2"].Value2.ToString());
}
退出excel程序
第一种
//得到当前打开的excel文件对象
Application excelApp = Marshal.GetActiveObject("EXCEL.Application") as Excel.Application;
excelApp.Quit();
excelApp = null;
第二种
Process.GetProcessesByName("EXCEL")[0].Kill();
excel相关
如何打开已有excel文档,或者创建一个新的excel文档
using Application = Microsoft.Office.Interop.Excel.Application;
using Microsoft.Office.Interop.Excel;
//EXCEL所存储的路径
string fileName = @"C:\Users\Administrator\Desktop\1.xlsx";
Application app = new Application();
app.Visible = true;
Workbooks wbks = app.Workbooks;
_Workbook _wbk = wbks.Add(fileName);
若打开已有excel,把“xxx”替换成该excel的文件路径;
注:若新建一个excel文档,“xxx”替换成true即可;不过这里新建的excel文档默认只有一个sheet。
sheet相关
取得、删除和添加sheet
获取sheet
//EXCEL所存储的路径
string fileName = @"C:\Users\Administrator\Desktop\1.xlsx";
Application app = new Application();
app.Visible = true;
Workbooks wbks = app.Workbooks;
_Workbook _wbk = wbks.Add(fileName);
//得到sheet的集合
Sheets shs = _wbk.Sheets;
//i是要取得的sheet的index
_Worksheet _wsh = (_Worksheet)shs.get_Item(1);
//得到sheet的名字 sheet1
MessageBox.Show(_wsh.Name);
删除sheet
//删除sheet必须的设置
app.DisplayAlerts = false;
_wsh.Delete();
常用属性
//根据索引获取感兴趣的数据表
Excel.Worksheet ws = wb.Worksheets[1];//sheet的索引从1开始
//获取工作表的名称
string wsName = ws.Name;
//数据表的行数
int wsRows = ws.Rows.Count;
//数据表的列数
int wsColumns = ws.Columns.Count;
//数据表的有效数据行数
int wsUsedRows = ws.UsedRange.Rows.Count;
//数据表的有效数据列数
int wsUsedColumns = ws.UsedRange.Columns.Count;