命名空间:Microsoft.Office.Interop.Excel
a. 创建Excel实例
Application excel = new Application();b. 打开已有的一个workbook
Workbook workbook = excel.Workbooks.Open(FilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);我查了资料Application是接口,怎么还可以实例化呀?

解决方案 »

  1.   

    string saveFileName = string.Empty;
      bool fileSaved = false;
      SaveFileDialog sfd = new SaveFileDialog();
      sfd.DefaultExt = "xls";
      sfd.Filter = "*.excel|*.xls";
      sfd.FileName = "TimTest";
      sfd.ShowDialog();
      saveFileName = sfd.FileName;
      if (saveFileName.IndexOf(':') < 0) return;
        
      Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
      if (excel == null) return;
      Microsoft.Office.Interop.Excel.Workbooks wbList = excel.Workbooks;
      Microsoft.Office.Interop.Excel.Workbook wb = wbList.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
      Microsoft.Office.Interop.Excel.Worksheet wsheet = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[1];
      DataTable dt = DBHelper.GetData();
      for (int i = 0; i < dt.Columns.Count; i++)
      {
      wsheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
      }
      for (int r = 0; r < dt.Rows.Count; r++)
      {
      for (int i = 0; i < dt.Columns.Count; i++)
      {
      wsheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
      }
      System.Windows.Forms.Application.DoEvents();
      }
      wsheet.Columns.EntireColumn.AutoFit();
      Microsoft.Office.Interop.Excel.Range rg = wsheet.get_Range(wsheet.Cells[2, 2], wsheet.Cells[dt.Rows.Count + 1, 2]);
      rg.NumberFormat = "00000000";
      if (saveFileName != "")
      {
      try
      {
      wb.Saved = true;
      wb.SaveCopyAs(saveFileName);
      fileSaved = true;
      }
      catch (Exception ex)
      {
      fileSaved = false;
      MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
      }
      }
      else
      {
      fileSaved = false;
      }
      excel.Quit();
      GC.Collect();
      if (fileSaved && System.IO.File.Exists(saveFileName))
      {
      System.Diagnostics.Process.Start(saveFileName);
      }要添加Microsoft 里面的excel引用
      

  2.   

    让我们看下它的定义:namespace Microsoft.Office.Interop.Excel
    {
        [Guid("000208D5-0000-0000-C000-000000000046")]
        [CoClass(typeof(ApplicationClass))]
        public interface Application : _Application, AppEvents_Event
        {
        }
    }看到没有,实际上你调用new实例化,是用的ApplicationClass这个类在实例化,这是方便你书写而已。
      

  3.   

    [CoClass(typeof(ApplicationClass))]
      [Guid("000208D5-0000-0000-C000-000000000046")]
      public interface Application : _Application, AppEvents_Event
      {
      }
    如上这个接口有GUID和CoClass属性修饰,因此代码
    application= new Excel.Application();
    会被翻译成
    application= new Excel.ApplicationClass();