asp.net导出Excel类库代码分享

代码如下:

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;

/// <summary>
///ExcelClass 的摘要说明
/// </summary>
public class ExcelClass
{
    /// <summary>
    /// 构建ExcelClass类
    /// </summary>
    public ExcelClass()
    {
        this.m_objExcel = new Excel.Application();
    }
    /// <summary>
    /// 构建ExcelClass类
    /// </summary>
    /// <param name="objExcel">Excel.Application</param>
    public ExcelClass(Excel.Application objExcel)
    {
        this.m_objExcel = objExcel;
    }

/// <summary>
    /// 列标号
    /// </summary>
    private string AList = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/// <summary>
    /// 获取描述区域的字符
    /// </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>
    /// 给单元格赋值1
    /// </summary>
    /// <param name="x">行号</param>
    /// <param name="y">列号</param>
    /// <param name="align">对齐(CENTER、LEFT、RIGHT)</param>
    /// <param name="text">值</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>
    /// 给单元格赋值2
    /// </summary>
    /// <param name="x">行号</param>
    /// <param name="y">列号</param>
    /// <param name="text">值</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>
    /// 给单元格赋值3
    /// </summary>
    /// <param name="x">行号</param>
    /// <param name="y">列号</param>
    /// <param name="text">值</param>
    /// <param name="font">字符格式</param>
    /// <param name="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>
    /// 插入新行
    /// </summary>
    /// <param name="y">模板行号</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>
    /// 把剪切内容粘贴到当前区域
    /// </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>
    /// 设置边框
    /// </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; //忽略的参数OLENULL
    private Excel.Application m_objExcel;//Excel应用程序实例
    private Excel.Workbooks m_objBooks;//工作表集合
    private Excel.Workbook m_objBook;//当前操作的工作表
    private Excel.Worksheet sheet;//当前操作的表格

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>
    /// 打开Excel文件
    /// </summary>
    /// <param name="filename">路径</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是判断xlApp是怎么启动的flag.
            {
                m_objExcel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
                //释放COM组件,其实就是将其引用计数减1
                //System.Diagnostics.Process theProc;
                foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                {
                    //先关闭图形窗口。如果关闭失败...有的时候在状态里看不到图形窗口的excel了,
                    //但是在进程里仍然有EXCEL.EXE的进程存在,那么就需要杀掉它:p
                    if (theProc.CloseMainWindow() == false)
                    {
                        theProc.Kill();
                    }
                }
                m_objExcel = null;
                return true;
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
}

/// <summary>
    /// 点击打印按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Sendbu_Click(object sender, EventArgs e)
    {
        try
        {         
            //查找部门分类用户
            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();//创建Excel操作类对象

int Ycount = 1;

Ec.CreateExceFile();//创建Excel文件

Ec.setValue(Ycount, 1, "CENTER", "组织部门");
            Ec.setValue(Ycount, 2, "CENTER", "姓名");
            Ec.setValue(Ycount, 3, "CENTER", "性别");
            Ec.setValue(Ycount, 4, "CENTER", "职位");
            Ec.setValue(Ycount, 5, "CENTER", "移动电话");
            Ec.setValue(Ycount, 6, "CENTER", "电话");
            Ec.setValue(Ycount, 7, "CENTER", "电子邮箱");
            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+"通讯录.xlsx");

//*******释放Excel资源***********
            Ec.ReleaseExcel();

Response.Redirect("Contactfiles/通讯录.xlsx");           
        }
        catch (Exception ex)
        {
            PageError("导出出错!"+ex.ToString(),"");
        }
    }

(0)

相关推荐

  • asp.net类库中添加WebService引用出现问题解决方法

    在Web项目内添加WebService的引用是件很简单的事情,今天在类库中添加WebService引用时候,却遇到了问题,特此记录下来. 1.添加服务引用. 2.点击高级 3.添加Web引用 4.看到了就跟Web项目添加WebService一样了 添加完成后,再次点击 添加引用就出现了添加Web引用了

  • asp.net 类库中使用ConfigurationManager.ConnectionStrings

    一直没弄明白怎么在类库中找不到 ConfigurationManager.ConnectionStrings 后面才发现没有添加System.configuration的引用,添加后: 引入命名空间: 复制代码 代码如下: using System.Configuration; 便可以使用了: 复制代码 代码如下: public static string ConnectionString = ConfigurationManager.ConnectionStrings["Conn"]

  • ASP.NET MVC 控制器与视图

    一.控制器相关 在Controller类中方法访问级别为public的方法,就是行为(Action).如果不希望Controller类中的方法成为Action(可以在地址栏中被访问),有两种实现方式:将方法的访问级别设置为private在方法上添加特性标记[NonAction] 诸如新增\修改等功能模块,我们往往会创建2个名称相同的Action:一个action用于加载新增\修改页面;另一个action用于处理新增\修改页面提交的表单数据.那么如何区分在何时调用哪个action呢? 我们将加载新

  • Asp.Net类库中发送电子邮件的代码

    通常验证电子邮件真实有效的办法是:当用户填写的注册资料经过网站初步格式验证之后,用户并不能利用此帐号登录,系统会向用户注册时填写的电子邮件地址发送一封电子邮件,邮件中给出一个链接,只有当用户点击了这个链接之后才能登录到网站,如果用户填写的电子邮件地址不是真实有效的或者不是他本人的,就不会收到这封电子邮件,这样仍然不能登录,这一步一般称之为电子邮件激活. 在.net类库中有两种发送电子邮件的方式,一种是在.net2.0以下版本中的做法,一种是.net2.0以上版本的做法.下面分别介绍这两种办法.

  • js插件类库组织与管理(基于asp.net管理)

    testjs插件类库组织与管理先举个例子,比如jquery插件中的calendar在一个页面中就得有如下代码 复制代码 代码如下: <style type="text/css"> @import ""script/calendar/jquery.datepick.css"; </style> <script type="text/javascript" src="script/jquery1.3.

  • ASP.NET MVC中将控制器分离到类库的实现

    前言 在.ASP.NET MVC的开发中,我们创建完项目之后,ASP.NET MVC是已Model-Controller-View的形式存在的,在创建项目自动生成的内容上Model我们很容易分离成类库,所以这里不予说明,那么这时候我们就像Controller是不是也能够分离出去呢?答案是肯定的,下面我们探讨一下Controller如何分离出去. 这里我提供两种分离的方法,一是重写方法继承自IControllerFactory接口,实现里面的方法,二是MVC提供了直接在路由注册里面去控制控制器的书

  • ASP.NET中MVC从后台控制器传递数据到前台视图的方式

    本文实例讲述了ASP.NET中MVC从后台控制器传递数据到前台视图的方式.分享给大家供大家参考.具体分析如下: 数据存储模型Model: 复制代码 代码如下: public class CalendarEvent { public string id { get; set; } public DateTime start { get; set; } public DateTime end { get; set; } public string backgroundColor { get; set

  • asp.net导出Excel类库代码分享

    复制代码 代码如下: using System;using System.Collections.Generic;using System.Reflection;using System.Web;using Excel = Microsoft.Office.Interop.Excel; /// <summary>///ExcelClass 的摘要说明/// </summary>public class ExcelClass{    /// <summary>    //

  • asp.net导出EXCEL的功能代码

    复制代码 代码如下: //由gridviw导出为Excel public static void ToExcel(System.Web.UI.Control ctl) { HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls"); HttpContext.Current.Response.Charset = "UTF-8

  • C#实现GridView导出Excel实例代码

    导出Excel在很多项目中经常用到,本人介绍了C#实现GridView导出Excel实例代码,也全当给自己留下个学习笔记了. using System.Data; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Text; namespace DotNet.Utilities { /// <summary> /// Summary desc

  • .net客户端导出Excel实现代码及注意事项

    客户端导出excel 复制代码 代码如下: /* * 将DataGrid导出为Excel文件 * * @param strTitle 文件标题 * @param dgData 待导出的DataGrid * @param iStartCol 起始列序号 * @param iEndCol 结束列序号 * * 创建人: calvin * 创建日期: 2005-10-08 * 修改人: * 修改日期:**/ function DataGrid2Excel(strTitle, dgData, iStart

  • asp.net导出excel数据的常见方法汇总

    本文实例讲述了asp.net中一些常用的excel数据导出方法,同时也介绍了在数据导入或导出时可能碰到的一些问题总结,分享给大家供大家参考.希望文章对你会有所帮助.具体实现方法如下: 1.由dataset生成 复制代码 代码如下: public void CreateExcel(DataSet ds,string typeid,string FileName)    {    HttpResponse resp;    resp = Page.Response;    resp.ContentE

  • js导入导出excel(实例代码)

    导入: 复制代码 代码如下: <html xmlns="http://www.w3.org/1999/xhtml" ><head>     <title>Untitled Page</title></head><script language="javascript" type="text/javascript">function importXLS(fileName){ 

  • ASP.net连接Excel的代码

    首先添加命名空间 复制代码 代码如下: using System.Data.OleDb; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { strfile = Request.QueryString["filename"];//从其他页面传过来的文件路径 Excel(strfile); } } private void Excel(string filepath) { try { Data

  • JS调用页面表格导出excel示例代码

    使用JS方法调用页面表格导出excel有很大的限制: 1.目前试了几个浏览器,只有IE支持, 2.点击 工具---安全---自定义级别---ActiveX 相关选项启用 下面是html代码 复制代码 代码如下: <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath()

  • asp.net导出excel的简单方法实例

    excel的操作,最常用的就是导出和导入,废话不多说上代码. 本例使用NPOI实现的,不喜勿喷哈.... 复制代码 代码如下: /// <summary>        /// 导出Excel        /// </summary>        /// <param name="stime"></param>        /// <param name="etime"></param> 

  • ASP.NET导出Excel打开时提示:与文件扩展名指定文件不一致解决方法

    "将页面显示的GridView中的数据,导出到Excel表格中"时遇到这样一个错误: C# 导出Excel文件 打开Excel文件格式与扩展名指定格式不一致.具体提示如图: 解决办法:这里采用"修改注册表的方法"解决此问题,这并没从根上解决问题: 1.打开注册表编辑器方法:开始 -> 运行 -> 输入regedit -> 确定 2.找到注册表子项HKEY_CURRENT_USER\Software\Microsoft\Office\12.0\Exc

随机推荐