Magicodes.IE.Excel

导出Excel 组件,非常好用的. 本人在使用过程中遇到的一些小小问题分享给大家注意的:

第一:注意字段不能有空格

第二:注意属性类型最好都是string类型

[HttpPost]
        [Route("[area]/[controller]/[action]")] 
        public IActionResult DownloadEmployee(DownloadEmployeeInput input)
        {
             
            ResponseModalX responseModalX = new ResponseModalX();
            DataBaseContext dataBaseContext = new DataBaseContext();
            if (!IsFrommApi)
            {
                input.MainComId = input.MainComId ?? WebCookieBase.MainComId;
            }
            if (CheckMaincomConsistency(input.MainComId) == false && IsFrommApi)
            {
                responseModalX.meta = new MetaModalX
                {
                    Success = false,
                    ErrorCode = (int)GeneralReturnCode.REQUIRED_CORRECT_PARMS_MAINCOM_ID,
                    Message = GeneralReturnCode.REQUIRED_CORRECT_PARMS_MAINCOM_ID.GetEnumDescription()
                };
                return Ok(responseModalX);
            }

var employeeLists = from s in dataBaseContext.Employee.Where(c => c.MainComId == input.MainComId)
                                select s;
            if (!String.IsNullOrEmpty(input.Search))
            {
                input.Search = WebUtility.UrlDecode(input.Search).Trim();
                employeeLists = employeeLists.Where(s => s.FirstName.Contains(input.Search)
                                       || s.LastName.Contains(input.Search)
                                       || s.CnName.Contains(input.Search)
                                       || s.Email.Contains(input.Search)
                                       || s.PhoneNumber.Contains(input.Search)
                                       || s.ContractorName.Contains(input.Search)
                                       || s.SiteName.Contains(input.Search)
                                       || s.DepartmentName.Contains(input.Search)
                                       || s.JobName.Contains(input.Search)
                                       || s.PhoneNumber.Contains(input.Search)
                                       || s.EmployeeId.Contains(input.Search));
            }

employeeLists = employeeLists.OrderBy(s => s.EnrollmentDate).OrderBy(c => c.OperatedDate);

if (employeeLists.Count()==0)
            {
                responseModalX.meta = new MetaModalX
                {
                    Success = false,
                    ErrorCode = (int)GeneralReturnCode.FAIL,
                    Message = GeneralReturnCode.LIST_NO_RECORD.GetEnumDescription()
                };
                return Ok(responseModalX);
            }

List<EmployeeExcel> employeeExcels = new List<EmployeeExcel>();
            foreach (var item in employeeLists)
            {
                AttEnumCode.ShiftBusiness.Genders genders = (AttEnumCode.ShiftBusiness.Genders)item.Gender;
                EmployeeExcel employeeExcel = new EmployeeExcel
                {
                    EmployeeId = item.EmployeeId,
                    UserId = item.UserId ?? string.Empty,
                    ParentUserId = item.ParentUserId ?? string.Empty,
                    UserIcon = item.UserIcon ?? string.Empty,
                    The3rdPartyEmployeeId = item.The3rdPartyEmployeeId ?? string.Empty,
                    CnName = item.CnName ?? string.Empty,
                    FirstName = item.FirstName ?? string.Empty,
                    LastName = item.LastName ?? string.Empty,
                    CompanyName = item.CompanyName ?? string.Empty,
                    ContractorName = item.ContractorName ?? string.Empty,
                    DepartmentName = item.DepartmentName ?? string.Empty,
                    SiteName = item.SiteName ?? string.Empty,
                    JobName = item.JobName ?? string.Empty,
                    PositionTitle = item.PositionTitle ?? string.Empty,
                    Email = item.Email ?? string.Empty,
                    PhoneNumber = item.PhoneNumber ?? string.Empty,
                    AccessCardId = item.AccessCardId ?? string.Empty,
                    FingerPrint = item.FingerPrint ?? string.Empty,
                    Birthday = string.Format("{0:yyyy-MM-dd}", item.Birthday),
                    CreatedDate = string.Format("{0:yyyy-MM-dd HH:mm:ss}", item.CreatedDate),
                    IsBlock = item.IsBlock == true ? "TRUE" : "FALSE",
                    EnrollmentDate = string.Format("{0:yyyy-MM-dd}", item.EnrollmentDate),
                    OperatedDate = string.Format("{0:yyyy-MM-dd HH:mm:ss}", item.OperatedDate),
                    IdNumber = item.IdNumber ?? string.Empty,
                    Gender = genders.GetEnumDescription(),
                    LeaveDate = string.Format("{0:yyyy-MM-dd}", item.LeaveDate),
                    OperatedUserName = item.OperatedUserName,
                    MainComId = item.MainComId,
                    Remarks = item.Remarks ?? string.Empty,
                };

employeeExcels.Add(employeeExcel);
            }
            string companyName = dataBaseContext.MainCom.Find(input.MainComId).CompanyName ;

EmployeeExcelStruct employeeExcelStruct = new EmployeeExcelStruct(companyName, string.Format("{0:yyyy-MM-dd}", DateTime.Now), employeeExcels);
             
            //Handle Download
            string tempFolder = Path.Combine(WebHostEnvironment.WebRootPath, UploadSetting.TargetFolder, "Temp");

if (!Directory.Exists(tempFolder))
            {
                Directory.CreateDirectory(tempFolder);
            }

string fileName = string.Format("{0}-{1:yyyyMMdd}.{2}.xlsx", WebCookieBase.MainComId, DateTime.Now, LangUtilities.LanguageCode);
            string pathFileName = Path.Combine(tempFolder, fileName);

string ExcelTemplate = Path.Combine(WebHostEnvironment.WebRootPath, UploadSetting.TargetFolder, "ExcelTemplate");
            string ExcelTemplateFileName = string.Format("EmployeeListRpt.{0}.xlsx", LangUtilities.LanguageCode);
            string ExcelTemplateFile = Path.Combine(ExcelTemplate, ExcelTemplateFileName);

//ExportByTemplateEmployee(ExcelTemplateFile, pathFileName, employeeExcelStruct).GetAwaiter().GetResult();

bool IsExist = false;
            if (System.IO.File.Exists(pathFileName))
            {
                FileInfo fileInfo = new FileInfo(pathFileName);
                if (Math.Abs(fileInfo.CreationTime.Subtract(DateTime.Now).TotalMinutes) > 30)
                {
                    IsExist = false;
                    ExportByTemplateEmployee(ExcelTemplateFile, pathFileName, employeeExcelStruct).GetAwaiter().GetResult();
                }
                else
                {
                    IsExist = true;
                }
            }
            else
            {
                ExportByTemplateEmployee(ExcelTemplateFile, pathFileName, employeeExcelStruct).GetAwaiter().GetResult();
            }

bool IsWait = true;
            int maxWaitTime = 20000;
            int i = 0;
            while (IsWait && !IsExist)
            {
                if (System.IO.File.Exists(pathFileName))
                {
                    IsExist = true;

FileInfo fileInfo = new FileInfo(pathFileName);
                    if (Math.Abs(fileInfo.CreationTime.Subtract(DateTime.Now).TotalMinutes) > 30)
                    {
                        IsWait = true;
                    }
                    else
                    {
                        IsWait = false;
                    }
                }
                else
                {
                    IsWait = true;
                    Thread.Sleep(500);
                }
                if (i * 500 > maxWaitTime)  //force to stop
                {
                    IsExist = true;
                    IsWait = false;

responseModalX = new ResponseModalX
                    {
                        meta = new MetaModalX { Success = false, ErrorCode = (int)GeneralReturnCode.FAIL, Message = "OVER TIME" },
                        data = null
                    };
                    return Ok(responseModalX);
                }
                i++;
            }

string downloadUrl = string.Format("{0}/Files/Tempcsv/{1}", HttpHost, fileName);
            responseModalX = new ResponseModalX();
            responseModalX.data = new { downloadUrl, fileName };

return Ok(responseModalX);
        }
        /// <summary>
        ///  ref https://www.cnblogs.com/codelove/p/12187037.html
        /// </summary>
        /// <param name="templatePathFileName"></param>
        /// <param name="PathFileName"></param>
        /// <param name="employeeExcelStruct"></param>
        /// <returns></returns>
        public async Task ExportByTemplateEmployee(string templatePathFileName, string PathFileName, EmployeeExcelStruct employeeExcelStruct)
        {
            //创建Excel导出对象  
            IExportFileByTemplate exporter = new ExcelExporter();

//根据模板导出  
            await exporter.ExportByTemplate(PathFileName, employeeExcelStruct, templatePathFileName);  //ref : https://www.cnblogs.com/codelove/p/12187037.html
        }

Magicodes.IE.Excel 用法注意 导出Excel 组件,非常好用的.相关推荐

  1. maatwebsite/Excel 3.0 导出 Excel 如何设置长数字为文本

    maatwebsite/Excel 3.0 导出 Excel 如何设置长数字为文本 我这里是 'C' 这几列是超过 15 位数字,自动转换为了科学计数法,所以直接绑定这几列即可. https://gi ...

  2. php 将数组导出excel,#php 怎样将 数组导出excel文件#前端导出excel表格

    php 怎样将 数组导出excel文件 public function excel() { //在这里你要导出的数据 $data = M('pmproject',"pm_",MYS ...

  3. angularjs 导出excel php,AngularJS 导出Excel指令

    Excel导出思路 项目中使用到了导出Excel功能,潘老师已经在博客中将表格导出为csv的技术难点实现,剩下的,只是根据实际的业务需求对该指令进行完善. 大体遇到了以下几个问题: 功能按钮不导出 因 ...

  4. 服务器不安装Excel,实现导出Excel功能

    /// <summary> /// 导出为Excel /// </summary> /// <param name="sender"></ ...

  5. 导出mysql excel数据字典_mysql导出 Excel数据字典(全)

    解决问题(有mysql数据库数据表想要将表导入到PowerDesigner 或导出Excel数据字典) 一.下载工具 1.工具PowerDesigner 百度自行下载安装 2.mysql-connec ...

  6. java 导出excel 例子_java导出Excel例子

    //在service层写的,在action直接调用此方法就行了 //导出Excel public boolean exportExcel(HttpServletResponse response,Li ...

  7. java 导出excel教程_Java导出Excel表格

    Java导出Excel表格 导出Excel表格需要一个poi-3.9.jar的包,该包在网上可以找到. 第一步,创建Excel对象. HSSFWorkbook workbook = new HSSFW ...

  8. java导出excel 乱码_java导出excel时出现文件名乱码解决方法

    java解决导出Excel时文件名乱码的方法示例:(推荐:java视频教程)String agent = request.getHeader("USER-AGENT").toLow ...

  9. 报表导出HTML格式怎么转换为EXCEL,使用html导出excel时的格式问题

    用写html的方法导出excel时,excel会自动把一些格式转换一下,有时达不预期的效果,此时可以通过样式进行调整下数据格式就可以了. 常用的几种: mso-number-format:\@ 文本 ...

最新文章

  1. DL练习1:基于boston_house_prices的BP神经网络
  2. 线性回归模型原理及推导
  3. TCP/IP总结(4)TCP 之3次握手
  4. Android中实现照片滑动时左右进出的动画的xml代码
  5. asp.net学习之SqlDataSource 2 select的四种参数赋予形式的解释
  6. BZOJ 2565: 最长双回文串
  7. 【Flink】Flink Row和RowData的区别
  8. 一键清理Quartus工程编译垃圾
  9. python根据uuid去重,获取请求重各种动作的次数
  10. 如何在网络视听行业建一扇内容安全大门?
  11. mysql索引和事务_mysql的索引和事务详细解读
  12. c++的size_t
  13. PHP:回退(Backed)枚举
  14. 美术生都要膜拜的AI,照片迅速被画成艺术画
  15. 实时数据同步利器debezium教程
  16. Daimayuan Online Judge 查重判断
  17. 按位与和异或运算符(Python中两个不常用,却重要的运算符)
  18. 计算机视觉:特征提取与匹配
  19. ava入门篇——如何编写一个简单的Java程序
  20. 字节跳动暑期实习面试题准备

热门文章

  1. Linux CentOS系统安装中文字体
  2. 高级程序员必修课--sql思维举重训练
  3. 局域网交换机和路由器
  4. 造纸行业报告:特种纸产业全球视角研究报告:以史为镜,开天辟地
  5. Beginning Android
  6. Beginning 创建之初
  7. 计算机二级Python操作题练习(第九套)
  8. 概述:隐式神经表示(Implicit Neural Representations,INRs)
  9. 「COCI 2018.10.20」Teoretičar
  10. DiffusionDet: Diffusion Model for Object Detection