关闭

导出到excel的类(一)

646人阅读 评论(0) 收藏 举报

using System;
using System.IO;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using RFID.PublicClass.DataBase;


namespace RFID.PublicClass.ExcelReport
{
 /// <summary>
 /// ExcelReport 的摘要说明。
 /// </summary>
 public class ExcelReport
 {
  private  static Excel.ApplicationClass ExcelApp = null;
  private   static Excel.Workbooks   ExcelBooks=null;
  private  static Excel.Workbook    ExcelBook=null;
  private static Excel.Worksheet   ExcelSheet=null;
  public static string FilePath=null;
  public static string FormPath=null;
    
        //构造函数,完成excel属性的付值。
  public ExcelReport(string OpenPath,string SavePath)
  {  

   try
   
   {   FormPath=OpenPath;//模板位置
    FilePath=SavePath;//excel文件位置
    ExcelApp=new Excel.ApplicationClass();
    object missing=Missing.Value;
    ExcelBooks=ExcelApp.Workbooks;
    ExcelBook=(Excel.Workbook)ExcelApp.Workbooks.Open(FormPath,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing,missing);
    ExcelSheet=(Excel.Worksheet)ExcelBook.ActiveSheet;
    ExcelApp.Visible=false;
    ExcelApp.DisplayAlerts=false; 
   }
   catch(Exception e)
   {
    CloseExcelForm();
       new Exception(e.Message);
   }
   //
   // TODO: 在此处添加构造函数逻辑
   //
  }
  public static void InsertExcel(DataSet dSet,int StartRow,int StartCol,string Table)
  { 
   try
   {         
          int RowCount=dSet.Tables[Table].Rows.Count;
    int ColCount=dSet.Tables[Table].Columns.Count;

    for(int i=StartRow;i<=(StartRow+RowCount-1);i++)
    {
     for(int j=StartCol;j<=(StartCol+ColCount-1);j++)
     {
      string values=dSet.Tables[Table].Rows[i-StartRow][j-StartCol].ToString();
      ExcelApp.Cells[i,j]=values;
     }
    } 
    dSet.Clear();
    ExcelSheet.SaveAs(FilePath,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
    ExcelSheet.Activate();
    ExcelApp.Visible=true;   

   }
   catch
   {
    CloseExcelForm();
   }           


  }
          
  ~ExcelReport()
   {
            CloseExcelForm();
   }
  public static void  CloseExcelForm()
  {
    try
   {
    ExcelBooks = null;
    ExcelBook = null;
    ExcelSheet = null;
    if(ExcelApp!= null)
    {
     ExcelApp.Quit();
     ExcelApp = null;
    }
   }
   finally
   {
    GC.Collect();
    GC.WaitForPendingFinalizers();
   }
  }  
 }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:157451次
    • 积分:1970
    • 等级:
    • 排名:千里之外
    • 原创:43篇
    • 转载:10篇
    • 译文:0篇
    • 评论:24条
    文章分类