asp.net 导出execl

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML.Excel;
using System.IO;
using System.Data;
using System.Web;
using System.Reflection;
using System.ComponentModel;

namespace VML.Blacklist.Web.Common.Utils
{
    public class ExcelHelper
    {
        public ExcelHelper()
        { }

        private DataTable dataTable = new DataTable();
        private StringBuilder builder = new StringBuilder();
        public PropertyInfo[] GetPropertyInfoArray(Type type)
        {
            PropertyInfo[] props = null;
            try
            {
                object obj = Activator.CreateInstance(type);
                //props = (from r in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                //         where r.GetCustomAttribute(typeof(DisplayNameAttribute)) != null
                //         select r).ToArray();

                props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .Select(x => new 
                        { 
                            Property = x, 
                            Attribute = (ExportAttribute)Attribute.GetCustomAttribute(x, typeof(ExportAttribute), true) 
                        })
                        .Where(x => x.Property.GetCustomAttribute(typeof(DisplayNameAttribute)) != null )
                        .OrderBy(x => x.Attribute != null ? x.Attribute.FieldOrder : -1)
                        .Select(x => x.Property )
                        .ToArray();
            }
            catch (Exception ex)
            {
                AppLogger.LogErrorOnly(ex);
            }
            return props;

        }

        public void AppendRow(PropertyInfo[] props)
        {
            if (props != null && props.Length > 0)
            {
                foreach (PropertyInfo prop in props)
                {
                    dataTable.Columns.Add(new DataColumn(prop.Name));
                }
                
            }
        }

        public void ExportDataToExcel(Type type, Object[] objectList, string fileName)
        {
            PropertyInfo[] props = GetPropertyInfoArray(type);
            AppendRow(props);
            foreach (object obj in objectList)
            {
                DataRow dr = dataTable.NewRow();
                for (int i = 0; i < props.Length; i++)
                {
                    dr[props[i].Name] = props[i].GetValue(obj, null) != null ? props[i].GetValue(obj, null) : "";
                }
                
                this.dataTable.Rows.Add(dr);
            }

            ExportDataToExcel(this.dataTable, fileName);
        }

        public void ExportDataToExcel(DataTable dt, string fileName)
        {
            using (XLWorkbook wb = new XLWorkbook())
            {

                var ws = wb.Worksheets.Add(dt, "ws");
                wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                wb.Style.Font.Bold = true;

                //set header style
                ws.Rows(1, 1).Style.Fill.BackgroundColor = XLColor.White;
                ws.Rows(1, 1).Style.Font.Bold = true;
                ws.Rows(1, 1).Style.Font.FontColor = XLColor.Onyx;
                ws.Columns().Width = 30;

                //remove AutoFilter
                ws.Tables.FirstOrDefault().ShowAutoFilter = false;

                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "utf-8";
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    wb.SaveAs(MyMemoryStream);
                    MyMemoryStream.WriteTo(HttpContext.Current.Response.OutputStream);
                    HttpContext.Current.Response.Flush();
                    HttpContext.Current.Response.End();
                }
            }
        }
    }
}
时间: 2024-08-09 22:40:20

asp.net 导出execl的相关文章

asp.net中导出Execl的方法

一.asp.net中导出Execl的方法: 在 asp.net中导出Execl有两种方法,一种是将导出的文件存放在服务器某个文件夹下面,然后将文件地址 输出在浏览器上:一种是将文件直接将文件输出流写给浏览器.在Response输出时,\t分隔的数据,导出 execl时,等价于分列,\n等价于换行. 1.将整个html全部输出execl 此法将html中所有的内容,如按钮,表格,图片等全部输出到Execl中.   Response.Clear();       Response.Buffer=  

asp.net大数据导出execl实现分开压缩并下载

asp.net大数据导出execl实现分开压缩并下载 /// <summary> /// 导出数据到EXCEL 多个表的 /// </summary> /// <param name="ds">数据集</param> /// <param name="AbosultedFilePath">导出的 EXCEL 路径</param> /// <param name="name&quo

Asp.net中利用NPOI组件快速导入导出Execl数据

相信很多童鞋都开发过Execl的导入导出功能,最近产品中无论是后台数据分析的需要,还是前端满足用户管理的方便,都有Execl导入导出的维护需求产生. 以前做这个功能,如果是web,利用HttpContext.Current.Response.ContentType ="application/ms-excel";就可以导出html数据表格到execl中,这种方法的问题就是编码格式的兼容性太差,用Mac OS之类的 office打开直接乱码给你看.或者是调用office的COM组件,或宏

在MySQL query browser中要导出execl表单

导出:  在MySQL query browser中要导出execl表单,只需要点击file,选择export execl就可以了(要先进入表单哦!). 导入: 数据库的数据太多一下导入有点麻烦,如何将excel的数据直接导入数据库呢? 第一步 另存为txt文档,名字最好为数据库的table名.  在这我们要保存问文本文件用制表符分割的那个,这样我们的数据就不会乱. 第二步 打开txt文档,点击另存为,修改编码,解决中文utf8.  这个时候的文件名必须和你要导入的table名称一样,否则在lo

asp mvc 导出txt 文件泛型方法

asp mvc 导出txt 文件泛型方法分享: public static void ExportFile<T>(T obj) { StringBuilder str = new StringBuilder(); //列出obj 对象中的所有属性 System.Reflection.PropertyInfo[] properties = obj.GetType().GetProperties(); if (properties != null && properties.Len

js导出execl兼容ie Chrome Firefox各种主流浏览器(js export execl)

第一种导出table布局的表格 <html> <head> <meta charset="utf-8"> <script type="text/javascript" language="javascript"> var idTmr; function getExplorer() { var explorer = window.navigator.userAgent; //ie if(explore

asp.net导出Excel

当在导出Execl或Word的时候,会发生只能在执行 Render() 的过程中调用 RegisterForEventValidation的错误提示.下面的2中方法是在网上找到的,没有应用:1.修改web.config(不推荐) <pages enableEventValidation ="false" ></pages> 2.直接在导出Execl的页面修改 <%@ Page Language="C#" AutoEventWireup=

Asp.net导出Excel乱码的解决方法

通过跟踪Asp.net服务器代码,没有乱码,然而导出Excel到浏览器后,打开时出现乱码. 解决方法是添加编码格式的前缀字节码:Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); ? 1 2 3 4 5 6 7 8 9 10 11 12 13 Response.Clear(); Response.AddHeader("content-disposition","attachment;filenam

mvc 导出execl

mvc导出execl 必须是get方法才可以  也不能使用ajax function ComplaintsExport() { var serial = $("form").serialize(); window.location.href = "/BidComplaints/Complaints/ComplaintsExport?" + serial; }; [HttpGet] [Description("导出")] public FileRe