C#中对Excel文件的操作

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

/// <summary>
/// ExportExcelretire 的摘要说明
/// </summary>
public class ExportExcelretire
{
   
private Excel.ApplicationClass ExcelObj = null;       //Excel对象
    private Excel._Workbook xBk;                         //工作薄
    private Excel._Worksheet xSt;                        //工作Sheet
    private string strTemplateFile;                         //模板文件
    private string strSavefile;                             //保存的文件
    private string strFile;
   
public ExportExcelretire()
    {
        System.Reflection.Missing miss
= System.Reflection.Missing.Value;
    }
   
#region 连接Excel
   
public int connectExcel(string templatName)
    {
       
try
        {
            strTemplateFile
= getTemplatePath(templatName); //模板文件
            ExcelObj = new Excel.ApplicationClass();
           
object missing = System.Reflection.Missing.Value;
           
if (templatName == "")
            {
                xBk
= ExcelObj.Workbooks.Add(true);
            }
           
else
            {

                xBk
= ExcelObj.Workbooks.Open(strTemplateFile,
                    missing, missing, missing, missing,
                    missing, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing);
            }

            xBk.SaveAs(getSaveFile(), Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            xSt
= (Excel._Worksheet)xBk.ActiveSheet;
           
return 1;
        }
       
catch (Exception e)
        {
           
string jj = e.Message.ToString();
           
return 0;
        }
    }
   
#endregion

   
#region 根据数据结果集,文件模板,开始行值生成Excel文件
   
/// <summary>
   
/// 根据数据结果集,文件模板,开始行值生成Excel文件
   
/// </summary>
   
/// <param name="ds">要传入到Excel的数据集</param>
   
/// <param name="strTitle">文件的标题</param>
   
/// <param name="templatName">文档模版</param>
   
/// <returns></returns>
    public int createTitleExcel(DataSet ds, string strTitle, string templatName)
    {
       
if (ds.Tables[0].Rows.Count == 0) return 0;

       
if (connectExcel(templatName) == 1)
        {
           
try
            {

                ExcelObj.Visible
= false;

                xSt.Cells[
2, 2] = ds.Tables[0].Rows[0]["xm"].ToString();
                xSt.get_Range(xSt.Cells[
2, 2], xSt.Cells[2, 2]).HorizontalAlignment = -4108;
                xSt.get_Range(xSt.Cells[
2, 2], xSt.Cells[2, 2]).Borders.LineStyle = 1;

                xSt.Cells[
2, 5] = ds.Tables[0].Rows[0]["xb"].ToString();
                xSt.get_Range(xSt.Cells[
2, 5], xSt.Cells[2, 5]).HorizontalAlignment = -4108;
                xSt.get_Range(xSt.Cells[
2, 5], xSt.Cells[2, 5]).Borders.LineStyle = 1;

                xSt.Cells[
2, 9] = ds.Tables[0].Rows[0]["csrq"].ToString();
                xSt.get_Range(xSt.Cells[
2, 9], xSt.Cells[2, 9]).HorizontalAlignment = -4108;
                xSt.get_Range(xSt.Cells[
2, 9], xSt.Cells[2, 9]).Borders.LineStyle = 1;
                xBk.Save();
            }
           
catch (Exception e)
            {
                Console.Write(e.GetBaseException());
                Console.Write(e.ToString());
               
return 0;
            }
           
finally
            {
                ExcelObj.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelObj);
                GC.Collect();

            }
        }
       
else
        {
           
if (xSt != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
                GC.Collect();
            }
           
if (xBk != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
                GC.Collect();
            }
           
if (ExcelObj != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ExcelObj);
                GC.Collect();
            }
           
return 0;
        }

       
return 1;
    }

   
#endregion

   
#region 根据传入的模版名设置绝对路径中的模板名
   
/// <summary>
   
/// 根据传入的模版名设置绝对路径中的模板名
   
/// </summary>
   
/// <param name="strTemplateName">模板名</param>
   
/// <returns></returns>
    private string getTemplatePath(string strTemplateName)
    {
       
string strTemplatePath = System.Configuration.ConfigurationSettings.AppSettings["TempletFilePath"];
        strTemplatePath
= AppDomain.CurrentDomain.BaseDirectory + strTemplatePath + strTemplateName;
       
return strTemplatePath;
    }
   
#endregion

   
#region  设置保存到临时文件中的文件名
   
/// <summary>
   
/// 设置保存到临时文件中的文件名
   
/// </summary>
   
/// <returns>临时文件名</returns>
    private string getSaveFile()
    {
       
string strSvaePath = System.Configuration.ConfigurationSettings.AppSettings["SaveFilePath"];
       
this.strFile = System.DateTime.Now.ToFileTimeUtc().ToString() + ".xls";
        strSavefile
= strSvaePath + this.strFile;
        strSvaePath
= AppDomain.CurrentDomain.BaseDirectory + strSavefile;
       
return strSvaePath;
    }
   
#endregion

   
#region 取得文件的相对路径
   
public string getVirteFile()
    {
       
return strSavefile;
    }
   
#endregion

   
#region 下载文件
   
/// <summary>
   
/// 下载文件
   
/// 传过一个带一个文件夹的文件
   
/// 如temp/12345.xls
   
/// </summary>
   
/// <param name="fileName"></param>
    public void DownloadExcelFile(string fileName, string FileNamefalse)
    {
       
if (fileName != "" && fileName != null)
        {
            System.IO.FileInfo file
= new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + fileName);
           
if (file.Exists)
            {
               
string FileName = FileNamefalse;
               
string ExtendName = file.Name;
               
if (ExtendName.Length > 4)
                {
                   
int i = ExtendName.LastIndexOf(".");
                    ExtendName
= ExtendName.Substring(i);
                    FileName
+= ExtendName;
                }
               
//Response.AppendHeader(@"Content-Disposition", @"attachment;filename=" + HttpUtility.UrlEncode("报表.xls",System.Text.Encoding.UTF8));
               
//这句话中的 attachment 改成 inline 就可以了
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader(
"Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
                HttpContext.Current.Response.AddHeader(
"Content-Length", file.Length.ToString());
                HttpContext.Current.Response.ContentType
= "application/octet-stream";
                HttpContext.Current.Response.Filter.Close();
                HttpContext.Current.Response.WriteFile(file.FullName);
                HttpContext.Current.Response.End();
            }
           
else
            {
                HttpContext.Current.Response.Write(
"对不起,文件" + AppDomain.CurrentDomain.BaseDirectory + fileName + "不存在");
            }
        }
    }
   
#endregion

}
posted @ 2009-06-11 00:38  貔貅  阅读(494)  评论(0编辑  收藏  举报