C# Excel操作的问题

cp298674954 2010-11-10 11:26:42
我是通过这样的方式实现的的但是 执行完毕以后 excel文件被加了锁 进程里还有一个Excel的进程。。。怎么解决呢。。。
using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Office.Core;
using ExcelAPI=Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;


namespace ExcelOrderReader
{
public class ExcelDocument
{
string filePath;

private ExcelAPI.Workbook workbook;
private ExcelAPI.Application app;

public ExcelDocument(string filePath)
{
this.filePath = filePath;
}

public ExcelAPI.Workbook OpenDocument()
{
return this.openDocument(filePath);
}

private ExcelAPI.Workbook openDocument(string fileName)
{
object MissingValue = Type.Missing;
this.app = new ExcelAPI.Application();
workbook = app.Workbooks.Open(fileName, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue, MissingValue, MissingValue,
MissingValue);
return workbook;
}

public void CloseDocument()
{
try
{
if (workbook!=null)
{
for (int i = 1; i < workbook.Sheets.Count; i++)
{
ExcelAPI.Worksheet workSheet = (ExcelAPI.Worksheet)workbook.Sheets[i];
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
workSheet = null;
}
workbook.Close(true, null, null);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
workbook = null;

if (app != null)
{
app.Workbooks.Close();
app.Quit();
KillSpecialExcel(app);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
app = null;

}
}
}
catch (Exception)
{
throw;
}
finally
{
GC.Collect();
}

}

#region 结束EXCEL.EXE进程的方法
/// <summary>
/// 结束EXCEL.EXE进程的方法
/// </summary>
/// <param name="m_objExcel">EXCEL对象</param>
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

public void KillSpecialExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
{
try
{
if (m_objExcel != null)
{
int lpdwProcessId;
GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
}
}
catch (Exception ex)
{
throw;
}
}
#endregion

~ExcelDocument()
{
CloseDocument();
}
}
}
...全文
103 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
cp298674954 2010-11-10
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bluedodo 的回复:]

开worker Thread
[/Quote]
多线程学的不太好。。。能否详细说明?
bluedodo 2010-11-10
  • 打赏
  • 举报
回复
开worker Thread
cp298674954 2010-11-10
  • 打赏
  • 举报
回复
100分啊 就是个悲剧
cp298674954 2010-11-10
  • 打赏
  • 举报
回复
悲剧啊 原来是在一个地方忘记CloseDocument了。。。。。。 Orz
孟子E章 2010-11-10
  • 打赏
  • 举报
回复

System.Runtime.InteropServices.Marshal.ReleaseComObject (各个对象);

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧