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();
}
}