zoukankan      html  css  js  c++  java
  • export to excel

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    npoi是重点。

    定义一个exporttoexcel的类

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using WindowsServer.Log;
    
    namespace Zige.Wechat.Common
    {
        public class ExportToExcel
        {
            private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
    
            public static void RenderToExcel2003<T>(List<T> datas, Stream stream)
            {
                IWorkbook workbook = null;
                ISheet sheet = null;
                IRow dtRow = null;
    
                try
                {
                    workbook = new HSSFWorkbook();
                    sheet = workbook.CreateSheet("会员表");
                    dtRow = sheet.CreateRow(0);
                    Type type = typeof(T);
                    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type);
    
                    //Data Header
                    ICell cell1 = dtRow.CreateCell(0);
                    cell1.SetCellValue("创建时间");
                    ICell cell2 = dtRow.CreateCell(1);
                    cell2.SetCellValue("昵称");
                    ICell cell3 = dtRow.CreateCell(2);
                    cell3.SetCellValue("手机号");
                    ICell cell4 = dtRow.CreateCell(3);
                    cell4.SetCellValue("安全密码");
                    ICell cell5 = dtRow.CreateCell(4);
                    cell5.SetCellValue("手机验证");
                    ICell cell6 = dtRow.CreateCell(5);
                    cell6.SetCellValue("状态");
    
    
                    int rowIndex = 1;
                    foreach (T data in datas)
                    {
                        object o = data;
                        dtRow = sheet.CreateRow(rowIndex);
                        for (int j = 0; j < properties.Count; j++)
                        {
                            PropertyDescriptor property = properties[j];
                            object value = property.GetValue(o);
                            ICell cell = dtRow.CreateCell(j);
                            if (j == 4) 
                            {
                                if (value.ToString()== "true")
                                { 
                                    value = "";
                                }
                                else 
                                {
                                    value = "";
                                }
                            }
                            if (j == 5)
                            {
                                if (value.ToString() == "true")
                                {
                                    value = "";
                                }
                                else
                                {
                                    value = "";
                                }
                            }
                            SetCellValue(cell, value);
                        }
                        rowIndex++;
                    }
    
                    workbook.Write(stream);
                    stream.Flush();
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Failed to export to excel.", ex);
                }
                finally
                {
                    stream.Close();
                    sheet = null;
                    workbook = null;
                }
            }
    
            public static void SetCellValue(ICell cell, object value)
            {
                try
                {
                    if (value is DateTime)
                    {
                        cell.SetCellType(CellType.String);
                        cell.SetCellValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    else if (value is TimeSpan)
                    {
                        cell.SetCellValue(new DateTime(1900, 1, 1) + (TimeSpan)value);
                    }
                    else if (value is int || value is short || value is float || value is double)
                    {
                        cell.SetCellValue(Convert.ToDouble(value));
                    }
                    else
                    {
                        cell.SetCellValue(value.ToString());
                    }
                }
                catch(Exception ex)
                {
                    _logger.ErrorException("Failed to set cell value.", ex);
                }
            }
    
        }
    }

    然后在api中调用方法

       using (ZigeDbContext db = Heart.CreateZigeDbContext())
                {
                    try
                    {
                        //var orders_1 = db.Database.SqlQuery<Order>(sqlText).ToList();
                        var parents = db.Parents.Select(p => new ParentInfo
                        {
                            CreatedTime = p.CreatedTime,
                            NickName=p.NickName,
                            PhoneNumber=p.PhoneNumber,
                            ProtectionPassword = p.ProtectionPassword,
                            IsPhoneNumberVerified=p.IsPhoneNumberVerified,
                            IsEnabled=p.IsEnabled,
                        }).OrderBy(or => or.CreatedTime).ToList();
                        //List<UserAccountInfo> users = db.Database.SqlQuery<UserAccountInfo>(sqlText, sqlParamterStartTime, sqlParameterEndTime).ToList();
    
    
                        string filePath = "~/Content/UploadFolder/" + "会员表" + "(导出时间" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ").xls";
                        if (System.IO.File.Exists(Server.MapPath(filePath)))
                        {
                            System.IO.File.Delete(Server.MapPath(filePath));
                        }
    
                        FileStream file = new FileStream(Server.MapPath(filePath), FileMode.Create);
                        ExportToExcel.RenderToExcel2003<ParentInfo>(parents, file);
                        var url = filePath.Substring(2, filePath.Length - 2);
                        var description = "导出日期:" + DateTime.Now.ToString();
                        //CMSLogUtility.WriteLog("导出OLO新注册用户", Guid.Empty, string.Empty, description);
                        return Json(new { Code = 1, Message = url }, JsonRequestBehavior.AllowGet);
                    }
                    catch (Exception ex)
                    {
    
                        throw (ex);
                    }
                }

    在js调用api

     $("#exportToExcel").on("click", function () {
            var url = getRawUrl("Parents/ExportToExcel");
           // $("#loading").show();
            $.ajax({
                url: url,
                type: "GET",
                cache: false,
                success: function (result) {
                    $("#loading").hide();
                    location.href = "http://" + location.host + baseServerUrl + result.Message;
                }, error: function () {
                    //$("#loading").hide();
                    alert("由于网络原因,导出失败!");
                }
            });
        });
  • 相关阅读:
    提取文件唯一标识符
    U盘出现很多.exe的文件处理方案
    winform做的excel与数据库的导入导出
    php获取数据库结构
    根据手机屏幕的旋转,调整图片
    c#中base64编码解码
    遮罩层的实现
    opencv车流量统计算法
    winform创建快捷方式
    mysql存储过程中like用法
  • 原文地址:https://www.cnblogs.com/tomahawk/p/4544523.html
Copyright © 2011-2022 走看看