using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
namespace testXls
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Example1 exam = new Example1();
exam.OperatorExcel();
}
public class Example1
{
private DateTime beforeTime; //Excel启动之前时间
private DateTime afterTime; //Excel启动之后时间
private string OriginalPath="e:\\testBefore.xls";
private string CurrentPath = "e:\\testAfter.xls";
public Example1()
{
}
public void OperatorExcel()
{
//GC.Collect();
Excel.Application excel; //声明excel对象
beforeTime = DateTime.Now; //获取excel开始启动时间
excel = new Excel.ApplicationClass(); //创建对象实例,这时在系统进程中会多出一个excel进程
afterTime = DateTime.Now; //获取excel启动结束的时间
try
{
object missing = System.Reflection.Missing.Value; //Missing 用于调用带默认参数的方法。
object readOnly = true;
excel.Visible = false; //是否显示excel文档
//Open Original Excel File
excel.Application.Workbooks.Open(OriginalPath, missing, readOnly, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
excel.Application.Workbooks.Add(true);
_Workbook myBook; //声明Workbook类
_Worksheet mySheet; //声明Worksheet类
myBook = excel.Workbooks[1]; //获取excel程序的工作簿
mySheet = (Worksheet)myBook.ActiveSheet; //获取Workbook的活动工作表(最上层的工作表)。
mySheet.Cells[1, 1] = "朝[A,1]单元格写入值";
//Save As Path
mySheet.SaveAs(CurrentPath, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//释放Excel对象,但在Asp.net Web程序中只有转向另一个页面的时候进程才结束
//可以考虑使用KillExcelProcess()杀掉进程
//ReleaseComObject 方法递减运行库可调用包装的引用计数。详细信息见MSDN
System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
myBook.Close(null, null, null);
excel.Workbooks.Close();
mySheet = null;
myBook = null;
missing = null;
excel.Quit();
excel = null;
}
catch
{
KillExcelProcess(); //杀掉进程
}
finally
{
//可以把KillExcelProcess();放在该处从而杀掉Excel的进程
}
}
private void KillExcelProcess()
{
System.Diagnostics.Process[] myProcesses;
DateTime startTime;
myProcesses = System.Diagnostics.Process.GetProcessesByName("Excel");
//得不到Excel进程ID,暂时只能判断进程启动时间
foreach (System.Diagnostics.Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
}
}
}
}
}
}