asp. net export Excel class library code sharing

  • 2020-09-16 07:26:09
  • OfStack


using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
/// <summary>
///ExcelClass  Summary description of 
/// </summary>
public class ExcelClass
{
    /// <summary>
    ///  build ExcelClass class 
    /// </summary>
    public ExcelClass()
    {
        this.m_objExcel = new Excel.Application();
    }
    /// <summary>
    ///  build ExcelClass class 
    /// </summary>
    /// <param name="objExcel">Excel.Application</param>
    public ExcelClass(Excel.Application objExcel)
    {
        this.m_objExcel = objExcel;
    }
    /// <summary>
    ///  The column label 
    /// </summary>
    private string AList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    /// <summary>
    ///  Gets the character for the description area 
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    public string GetAix(int x, int y)
    {
        char[] AChars = AList.ToCharArray();
        if (x >= 26) { return ""; }
        string s = "";
        s = s + AChars[x - 1].ToString();
        s = s + y.ToString();
        return s;
    }
    /// <summary>
    ///  Assign a value to a cell 1
    /// </summary>
    /// <param name="x"> The line Numbers </param>
    /// <param name="y"> Column number </param>
    /// <param name="align"> Alignment ( CENTER , LEFT , RIGHT ) </param>
    /// <param name="text"> value </param>
    public void setValue(int y, int x, string align, string text)
    {
        Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
        range.set_Value(miss, text);
        if (align.ToUpper() == "CENTER")
        {
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
        }
        if (align.ToUpper() == "LEFT")
        {
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;
        }
        if (align.ToUpper() == "RIGHT")
        {
            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
        }

    }
    /// <summary>
    ///  Assign a value to a cell 2
    /// </summary>
    /// <param name="x"> The line Numbers </param>
    /// <param name="y"> Column number </param>
    /// <param name="text"> value </param>
    public void setValue(int y, int x, string text)
    {
        Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
        range.set_Value(miss, text);
    }
    /// <summary>
    ///  Assign a value to a cell 3
    /// </summary>
    /// <param name="x"> The line Numbers </param>
    /// <param name="y"> Column number </param>
    /// <param name="text"> value </param>
    /// <param name="font"> Character format </param>
    /// <param name="color"> color </param>
    public void setValue(int y, int x, string text, System.Drawing.Font font, System.Drawing.Color color)
    {
        this.setValue(x, y, text);
        Excel.Range range = sheet.get_Range(this.GetAix(x, y), miss);
        range.Font.Size = font.Size;
        range.Font.Bold = font.Bold;
        range.Font.Color = color;
        range.Font.Name = font.Name;
        range.Font.Italic = font.Italic;
        range.Font.Underline = font.Underline;
    }
    /// <summary>
    ///  Insert a new row 
    /// </summary>
    /// <param name="y"> The template line number </param>
    public void insertRow(int y)
    {
        Excel.Range range = sheet.get_Range(GetAix(1, y), GetAix(25, y));
        range.Copy(miss);
        range.Insert(Excel.XlDirection.xlDown, miss);
        range.get_Range(GetAix(1, y), GetAix(25, y));
        range.Select();
        sheet.Paste(miss, miss);

    }
    /// <summary>
    ///  Paste the cut and paste into the current area 
    /// </summary>
    public void past()
    {
        string s = "a,b,c,d,e,f,g";
        sheet.Paste(sheet.get_Range(this.GetAix(10, 10), miss), s);
    }
    /// <summary>
    ///  Set the border 
    /// </summary>
    /// <param name="x1"></param>
    /// <param name="y1"></param>
    /// <param name="x2"></param>
    /// <param name="y2"></param>
    /// <param name="Width"></param>
    public void setBorder(int x1, int y1, int x2, int y2, int Width)
    {
        Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), miss);

        ((Excel.Range)range.Cells[x1, y1]).ColumnWidth = Width;
    }
    public void mergeCell(int x1, int y1, int x2, int y2)
    {
        Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
        range.Merge(true);
    }
    public Excel.Range getRange(int x1, int y1, int x2, int y2)
    {
        Excel.Range range = sheet.get_Range(this.GetAix(x1, y1), this.GetAix(x2, y2));
        return range;
    }
    private object miss = Missing.Value; // Ignored parameter OLENULL 
    private Excel.Application m_objExcel;//Excel Application instance  
    private Excel.Workbooks m_objBooks;// Worksheet set  
    private Excel.Workbook m_objBook;// The worksheet for the current operation  
    private Excel.Worksheet sheet;// The table of the current operation 
    public Excel.Worksheet CurrentSheet
    {
        get
        {
            return sheet;
        }
        set
        {
            this.sheet = value;
        }
    }
    public Excel.Workbooks CurrentWorkBooks
    {
        get
        {
            return this.m_objBooks;
        }
        set
        {
            this.m_objBooks = value;
        }
    }
    public Excel.Workbook CurrentWorkBook
    {
        get
        {
            return this.m_objBook;
        }
        set
        {
            this.m_objBook = value;
        }
    }
    /// <summary>
    ///  Open the Excel file 
    /// </summary>
    /// <param name="filename"> The path </param>
    public void OpenExcelFile(string filename)
    {
        UserControl(false);
        m_objExcel.Workbooks.Open(filename, miss, miss, miss, miss, miss, miss, miss,
                               miss, miss, miss, miss, miss, miss, miss);
        m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
        m_objBook = m_objExcel.ActiveWorkbook;
        sheet = (Excel.Worksheet)m_objBook.ActiveSheet;
    }
    public void UserControl(bool usercontrol)
    {
        if (m_objExcel == null) { return; }
        m_objExcel.UserControl = usercontrol;
        m_objExcel.DisplayAlerts = usercontrol;
        m_objExcel.Visible = usercontrol;
    }
    public void CreateExceFile()
    {
        UserControl(false);
        m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
        m_objBook = (Excel.Workbook)(m_objBooks.Add(miss));
        sheet = (Excel.Worksheet)m_objBook.ActiveSheet;
    }
    public void SaveAs(string FileName)
    {
         m_objBook.SaveAs(FileName, miss, miss, miss, miss,
         miss, Excel.XlSaveAsAccessMode.xlNoChange,
         Excel.XlSaveConflictResolution.xlLocalSessionChanges,
         miss, miss, miss, miss);
        //m_objBook.Close(false, miss, miss); 
    }
    public void ReleaseExcel()
    {
        m_objExcel.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objExcel);
        System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBooks);
        System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBook);
        System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);
        m_objExcel = null;
        m_objBooks = null;
        m_objBook = null;
        sheet = null;
        GC.Collect();
    }
    public bool KillAllExcelApp()
    {
        try
        {
            if (m_objExcel != null) // isRunning Is a judgment xlApp How does it start flag.
            {
                m_objExcel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
                // The release of COM Component, which is simply subtracting its reference count 1
                //System.Diagnostics.Process theProc;
                foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                {
                    // Close the graphics window first. If closing fails ... Sometimes you can't see the graphics window in the state excel Now, 
                    // But it's still in the process EXCEL.EXE The process exists, so you need to kill it :p
                    if (theProc.CloseMainWindow() == false)
                    {
                        theProc.Kill();
                    }
                }
                m_objExcel = null;
                return true;
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
}
   /// <summary>
    ///  Click the Print button event 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Sendbu_Click(object sender, EventArgs e)
    {
        try
        {          
            // Find department categories of users 
            DataTable Duser = EduOA.DBUtility.DbHelperSQL.Query("select count(*) as count,d.Id as DId FROM OA_User u,OA_Department d where u.DepartmentID=d.Id  group by d.Id").Tables[0];
            ExcelClass Ec = new ExcelClass();// create Excel Operation class object 
            int Ycount = 1;
            Ec.CreateExceFile();// create Excel file 
            Ec.setValue(Ycount, 1, "CENTER", " The organization department ");
            Ec.setValue(Ycount, 2, "CENTER", " The name ");
            Ec.setValue(Ycount, 3, "CENTER", " gender ");
            Ec.setValue(Ycount, 4, "CENTER", " position ");
            Ec.setValue(Ycount, 5, "CENTER", " The mobile phone ");
            Ec.setValue(Ycount, 6, "CENTER", " The phone ");
            Ec.setValue(Ycount, 7, "CENTER", " email ");
            Ec.setBorder(1, 1, 1, 1, 50);
            Ec.setBorder(1, 2, 2, 2, 20);
            Ec.setBorder(1, 5, 5, 5, 20);
            Ec.setBorder(1, 6, 6, 6, 20);
            Ec.setBorder(1, 7, 7, 7, 20);
            for (int i = 0; i < Duser.Rows.Count; i++)
            {
                Ycount += 1;
                Ec.setValue(Ycount, 1, "CENTER", Common.DeleteHtml(Getdept(Duser.Rows[i]["count"], Duser.Rows[i]["DId"])));
                DataTable dtuser = GetData(Duser.Rows[i]["DId"]);
                for (int k = 0; k < dtuser.Rows.Count; k++)
                {
                    Ec.setValue(Ycount, 2, "CENTER", dtuser.Rows[k]["TrueName"].ToString());
                    Ec.setValue(Ycount, 3, "CENTER", dtuser.Rows[k]["sex"].ToString());
                    Ec.setValue(Ycount, 4, "CENTER", dtuser.Rows[k]["PositionId"].ToString());
                    Ec.setValue(Ycount, 5, "CENTER", dtuser.Rows[k]["Telephone"].ToString());
                    Ec.setValue(Ycount, 6, "CENTER", dtuser.Rows[k]["Mobile"].ToString());
                    Ec.setValue(Ycount, 7, "CENTER", dtuser.Rows[k]["Email"].ToString());
                    Ycount += 1;
                }
            }
            string path = Server.MapPath("Contactfiles\\");
            Ec.SaveAs(path+" The address book .xlsx");
            //******* The release of Excel resources ***********
            Ec.ReleaseExcel();
            Response.Redirect("Contactfiles/ The address book .xlsx");            
        }
        catch (Exception ex)
        {
            PageError(" Error exporting! "+ex.ToString(),"");
        }
    }


Related articles: