Excel 操作结束后,防止程序还在使用

using ConExcel = Microsoft.Office.Interop.Excel;

try

{

ConExcel.Application xlApp = new ConExcel.Application();

ConExcel.Workbooks workbooks = xlApp.Workbooks;
ConExcel.Workbook workbook = workbooks.Add(ConExcel.XlWBATemplate.xlWBATWorksheet);

ConExcel.Worksheet worksheet = (ConExcel.Worksheet)workbook.Worksheets.get_Item(workbook.Worksheets.Count);
workbook.Worksheets.Add(Type.Missing, worksheet, Type.Missing, Type.Missing);//取得sheet1

//保存Excel

int FormatNum;//保存excel文件的格式
string Version;//excel版本号
Version = xlApp.Version;//获取你使用的excel 的版本号
if (Convert.ToDouble(Version) < 12)//You use Excel 97-2003
{
FormatNum = -4143;
}
else//you use excel 2007 or later
{
FormatNum = 56;
}

workbook.Saved = true;

workbook.SaveAs(@"" + “在服务端中的文件相对路径path”,
FormatNum, Missing.Value, Missing.Value,
false, false, ConExcel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


File.Copy(path, newPath);

//下载Excel文件

FileInfo fi = new FileInfo(newPath);//excelFile为文件在服务器上的地址
HttpResponse contextResponse = HttpContext.Current.Response;
contextResponse.Redirect(string.Format(newPag + "{0}", "BoxTag.xls"), false);
contextResponse.Clear();
contextResponse.Buffer = true;
contextResponse.Charset = "GB2312";
System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("BoxTag.xls", System.Text.Encoding.UTF8));
contextResponse.AppendHeader("Content-Length", fi.Length.ToString());
contextResponse.ContentEncoding = Encoding.Default;
contextResponse.ContentType = "application/vnd.ms-excel";
this.Page.EnableViewState = false;
contextResponse.WriteFile(fi.FullName);
contextResponse.Flush();
fi.Delete();
HttpContext.Current.ApplicationInstance.CompleteRequest();

}

catch

{

 

}

finally

{

if (xlApp != null)
{
if (workbook != null)
{
workbook.Close(false, null, null);
Marshal.ReleaseComObject(workbook);
workbook = null;
}
xlApp.Workbooks.Close();
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}

}

posted on 2012-04-11 14:11  Jack.leung 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jack-liang/archive/2012/04/11/2442284.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值