c#实现根据模板导出

后台主要代码,主要根据NPOI来实现excel的读写(里面的赋值逻辑自己修改)

    #region 数据导出到历史变化excel
        /// <summary>
        /// 
        /// </summary>
        /// <param name="list">数据集合</param>
        /// <param name="date_now">excel文件名拼接字符串  生成方式 DateTime.Now.ToString("yyyyMMddHHmmss");</param>
        /// <param name="templateAbsolutePath">存放模板的据对路径  C:/UAF/FileUpload/Template/    说明一点模板是放在服务器上的,服务器存放模板的句对路径</param>
        /// <param name="templateName">模板名称</param>
        /// <param name="downExcelPath">存放数据生成的excel文件   C:/UAF/FileUpload/downExcel/</param>
        /// <returns></returns>
        public bool HistoryListToExcel(List<HistoricalQuestionsResultDto.ProblemSummaryData> list, string date_now, string templateAbsolutePath, string templateName, string downExcelPath)
        {
            #region 声明变量
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            FileStream file = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            #endregion

            try
            {
                if (list != null && list.Count > 0)
                {
                    //打开Excel模板文件 , 我这里有一个模板Excel文件 , 数据全部写入模板文件
                    // 放置模板的绝对地址
                    file = new FileStream(templateAbsolutePath + templateName, FileMode.Open, FileAccess.Read);

                    //这里可能会报错 , 是因为系统Excel版本不对应的原因 , 就像Ajax在IE和其他浏览器的声明 , 但我一直找不到好的解决方案 , 如果你有更好的 , 也可以分享一下 , 我这里仅作参考代码
                    workbook = new XSSFWorkbook(file);

                    sheet = workbook.GetSheetAt(0);//获取Excel 中 的sheet  
                    int rowCount = list.Count;//查询出数据的row count   数据行

                    #region 设置Cell边框样式

                    ICellStyle style = workbook.CreateCellStyle();

                    style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    style.BottomBorderColor = HSSFColor.Black.Index;
                    style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    style.LeftBorderColor = HSSFColor.Black.Index;
                    style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    style.RightBorderColor = HSSFColor.Black.Index;
                    style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    style.TopBorderColor = HSSFColor.Black.Index;

                    #endregion

                    // 居中
                    style.Alignment = HorizontalAlignment.Center;

                    // 单独设置一格数据
                    row = sheet.GetRow(1);  //获取第二行
                    //row.GetCell(1).SetCellValue(list[0].customName);//设置Cell的值 客户名称
                    //row.GetCell(1).CellStyle = style;
                    row.GetCell(3).SetCellValue(list[0].vehicleTypeName);//设置Cell的值 车型
                    //row.GetCell(3).CellStyle = style;
                    //设置每行每列的单元格  
                    for (int i = 0; i < rowCount; i++)
                    {
                        // 我这里 + 5是因为我的模板前五行都有标头数据
                        row = sheet.CreateRow(i + 5);
                        
                        // 序号
                        row.CreateCell(0).SetCellValue(i + 1);
                        row.GetCell(0).CellStyle = style;
                        // 车间
                        row.CreateCell(1).SetCellValue(list[i].workshopName);
                        row.GetCell(1).CellStyle = style;
                        // 产线
                        row.CreateCell(2).SetCellValue(list[i].lineName);
                        row.GetCell(2).CellStyle = style;
                        // 工位
                        row.CreateCell(3).SetCellValue(list[i].positionName);
                        row.GetCell(3).CellStyle = style;
                        // 工位长
                        row.CreateCell(4).SetCellValue(list[i].positionLeader);
                        row.GetCell(4).CellStyle = style;

                        // 历史问题
                        row.CreateCell(5).SetCellValue(list[i].problemDescribtion);
                        row.GetCell(5).CellStyle = style;
                        // 待验证或预案
                        row.CreateCell(6).SetCellValue(list[i].toBeVerified);
                        row.GetCell(6).CellStyle = style;
                        // 责任人
                        row.CreateCell(7).SetCellValue(list[i].responsiblePerson);
                        row.GetCell(7).CellStyle = style;
                        // 产中验证结果
                        row.CreateCell(8).SetCellValue(list[i].checkResultName);
                        row.GetCell(8).CellStyle = style;
                        // 升级处理标识
                        row.CreateCell(9).SetCellValue(list[i].upgradeFlagName);
                        row.GetCell(9).CellStyle = style;
                        // 备注
                        row.CreateCell(10).SetCellValue(list[i].remark);
                        row.GetCell(10).CellStyle = style;
                    }

                }


                if (!System.IO.Directory.Exists(downExcelPath))
                {
                    System.IO.Directory.CreateDirectory(downExcelPath);//不存在就创建目录 
                }

                using (fs = File.OpenWrite(downExcelPath + "历史问题" + date_now + ".xlsx"))
                {
                    workbook.Write(fs);//向打开的这个xls文件中写入数据  
                    result = true;
                }

                return result;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                file.Close();
                return false;
            }
        }

        #endregion

      

如果想用datatable操作数据而不用集合,可以用下面的类转换,且赋值逻辑自己修改

        #region 将泛类型集合List类转换成DataTable
        /// <summary>
        /// 将泛类型集合List类转换成DataTable
        /// </summary>
        /// <param name="list">泛类型集合</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(List<T> entitys)
        {
            //检查实体集合不能为空
            if (entitys == null || entitys.Count < 1)
            {
                throw new Exception("需转换的集合为空");
            }
            //取出第一个实体的所有Propertie
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();

            //生成DataTable的structure
            //生产代码中,应将生成的DataTable结构Cache起来,此处略
            DataTable dt = new DataTable();
            for (int i = 0; i < entityProperties.Length; i++)
            {
                //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
                dt.Columns.Add(entityProperties[i].Name);
            }
            //将所有entity添加到DataTable中
            foreach (object entity in entitys)
            {
                //检查所有的的实体都为同一类型
                if (entity.GetType() != entityType)
                {
                    throw new Exception("要转换的集合元素类型不一致");
                }
                object[] entityValues = new object[entityProperties.Length];
                for (int i = 0; i < entityProperties.Length; i++)
                {
                    entityValues[i] = entityProperties[i].GetValue(entity, null);
                }
                dt.Rows.Add(entityValues);
            }
            return dt;
        }


        #endregion

调用方法,


 /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        /// 
        public ReturnResult ExportHistoricalQuestionsData(HistoricalQuestionsResultDto param)
        {
            var msg = new ReturnResult()
            {
                Code = "S",
                Message = ""
            };
            try
            {
                ExportExcelService server2 = new ExportExcelService();
                // 获取模板绝对路径
                using (var db = new DapperContext())
                {
                    #region 这里放置的是几个路径,在数据库中存取,按自己具体修改

                    // 模板放置的绝对路径  C:/UAF/FileUpload/Template/
                    var templateAbsolutePath = db.QueryFirstOrDefault<SystemCfgDetail>(x => x.IsDeleted == false && x.MKey == "FileDownload" && x.MValue1 == "0").MValue4;
                    if (templateAbsolutePath == null | templateAbsolutePath == "")
                    {
                        return new ReturnResult
                        {
                            Code = "E",
                            Message = "模板放置的绝对路径未配置!"
                        };

                    }

                    // 供下载的备份文件夹 C:/UAF/FileUpload/downExcel/
                    var downExcelPath = db.QueryFirstOrDefault<SystemCfgDetail>(x => x.IsDeleted == false && x.MKey == "ExportByTemplate" && x.MValue1 == "0").MValue2;
                    if (downExcelPath == null | downExcelPath == "")
                    {
                        return new ReturnResult
                        {
                            Code = "E",
                            Message = "供下载的备份文件夹未配置!"
                        };
                    }
                    // 供下载的备份文件夹相对地址  http://192.168.110.216/FileUpload/downExcel/
                    var downExcelPath2 = db.QueryFirstOrDefault<SystemCfgDetail>(x => x.IsDeleted == false && x.MKey == "ExportByTemplate" && x.MValue1 == "1").MValue2;
                    if (downExcelPath2 == null | downExcelPath2 == "")
                    {
                        return new ReturnResult
                        {
                            Code = "E",
                            Message = "供下载的备份文件夹未配置!"
                        };

                    }

                    #endregion

                    var serviceExcel = new ExportExcelService();
                    var date1 = DateTime.Now.ToString("yyyyMMddHHmmss");
                    var bl = false;
                    var ff = "历史问题" + date1 + ".xlsx";
                    bl = serviceExcel.HistoryListToExcel(param.problemSummaryDatas, date1, templateAbsolutePath, "历史问题清单模板.xlsx", downExcelPath);
                    if (bl)
                    {
                        msg.Code = "S";
                        msg.Message = downExcelPath2 + ff;
                        return msg;
                    }
                    else
                    {
                        return new ReturnResult
                        {
                            Code = "E",
                            Message = "导出失败,请联系管理员!"
                        };
                    }
                }
            }
            catch (Exception e)
            {
                msg.Code = "E";
                msg.Msg = e.ToString();
                return msg;
            }
        }

最后的下载路径返回前台

前台js接收  (result.data就是后台传回来的下载excel具体路径,是根据ip的)

                        // window.open(result.data);   // window.open会出现页面刷新问题
                        window.location.href = result.data;

服务器存放的文件夹先在iis服务器配置好

这样就可以将备下载文件放在服务器本地,例如:C:/UAF/FileUpload/downExcel/文件

然后用服务器地址下载,例如:http://ip/FileUpload/downExcel/文件

 

参考链接     参考excel样式修改链接

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值