Beispiel #1
0
        /// <summary>
        /// 根据选中的ID记录,生成对应的PDF报表,返回路径
        /// </summary>
        /// <param name="ids">选中的ID记录,逗号分开</param>
        /// <returns></returns>
        public ActionResult ExportPdfWithGridPlus(string ids)
        {
            ActionResult result = Content("");

            if (!string.IsNullOrEmpty(ids))
            {
                //利用接口获取列表数据
                var list = BLLFactory <Asset> .Instance.FindByIDs(ids);

                //报表文件路径
                string reportPath = "/Report/barcode.grf";
                //转换为物理路径
                reportPath = Server.MapPath(reportPath);

                //导出PDF的文件路径
                string exportPdfPath = string.Format("/GenerateFiles/{0}/AssetReport.pdf", CurrentUser.Name);
                //转换为物理路径
                string realPath = Server.MapPath(exportPdfPath);
                //确保目录生成
                string parentPath = Directory.GetParent(realPath).FullName;
                DirectoryUtil.AssertDirExist(parentPath);

                //生成PDF报表文档到具体文件
                GridExportHelper helper  = new GridExportHelper(reportPath);
                bool             success = helper.ExportPdf(list, realPath, HttpContext);
                if (success)
                {
                    result = Content(exportPdfPath); //返回Web相对路径
                }
                helper.Dispose();                    //销毁对象
            }
            return(result);
        }
Beispiel #2
0
        public override bool Delete(object key)
        {
            FileUploadInfo info = this.FindByID(key);

            if ((info != null) && !string.IsNullOrEmpty(info.SavePath))
            {
                string path = Path.Combine(info.BasePath, info.SavePath.Trim(new char[] { '\\' }));
                if (!Path.IsPathRooted(path))
                {
                    path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path);
                    if (File.Exists(path))
                    {
                        try
                        {
                            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine(info.BasePath, "DeletedFiles"));
                            DirectoryUtil.AssertDirExist(filePath);
                            string str3 = Path.Combine(filePath, info.FileName);
                            str3 = this.method_1(str3, 1);
                            File.Move(path, str3);
                        }
                        catch (Exception exception)
                        {
                            LogTextHelper.Error(exception);
                        }
                    }
                }
            }
            return(base.Delete(key));
        }
Beispiel #3
0
        /// <summary>
        /// 删除指定的ID记录,如果是相对目录的文件则移除文件到DeletedFiles文件夹里面
        /// </summary>
        /// <param name="key">记录ID</param>
        /// <returns></returns>
        public override bool Delete(object key, DbTransaction trans = null)
        {
            //删除记录前,需要把文件移动到删除目录下面
            FileUploadInfo info = FindByID(key, trans);

            if (info != null && !string.IsNullOrEmpty(info.SavePath))
            {
                string serverRealPath = Path.Combine(info.BasePath, info.SavePath.Trim('\\'));
                if (!Path.IsPathRooted(serverRealPath))
                {
                    //如果是相对目录,加上当前程序的目录才能定位文件地址
                    serverRealPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, serverRealPath);

                    //如果是相对目录的,移动到删除目录里面
                    if (File.Exists(serverRealPath))
                    {
                        try
                        {
                            string deletedPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine(info.BasePath, "DeletedFiles"));
                            DirectoryUtil.AssertDirExist(deletedPath);

                            string newFilePath = Path.Combine(deletedPath, info.FileName);
                            newFilePath = GetRightFileName(newFilePath, 1);
                            File.Move(serverRealPath, newFilePath);
                        }
                        catch (Exception ex)
                        {
                            LogTextHelper.Error(ex);
                        }
                    }
                }
            }

            return(base.Delete(key, trans));
        }
Beispiel #4
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (this.listView1.CheckedItems.Count == 0)
            {
                MessageDxUtil.ShowTips("请勾选下载的文件!");
                return;
            }
            StringBuilder sb = new StringBuilder();

            string path = FileDialogHelper.OpenDir();

            if (!string.IsNullOrEmpty(path))
            {
                DirectoryUtil.AssertDirExist(Path.GetDirectoryName(path));

                #region  载保存图片
                bool hasError = false;

                foreach (ListViewItem item in this.listView1.CheckedItems)
                {
                    if (item != null && item.Tag != null)
                    {
                        string id = item.Tag.ToString();

                        try
                        {
                            FileUploadInfo fileInfo = BLLFactory <FileUpload> .Instance.Download(id);

                            if (fileInfo != null && fileInfo.FileData != null)
                            {
                                string filePath = Path.Combine(path, fileInfo.FileName);
                                FileUtil.CreateFile(filePath, fileInfo.FileData);
                            }
                        }
                        catch (Exception ex)
                        {
                            hasError = true;
                            sb.Append(ex.Message + "\r\n");
                            LogHelper.WriteLog(LogLevel.LOG_LEVEL_CRIT, ex, typeof(FrmAttachmentGroupView));
                        }
                    }
                }
                #endregion

                if (hasError)
                {
                    MessageDxUtil.ShowError(sb.ToString());
                }
                else
                {
                    System.Diagnostics.Process.Start(path);
                }
            }
        }
        public ActionResult Upload(HttpPostedFileBase fileData, string guid, string folder)
        {
            CommonResult result = new CommonResult();

            if (fileData != null)
            {
                try
                {
                    ControllerContext.HttpContext.Request.ContentEncoding  = Encoding.GetEncoding("UTF-8");
                    ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                    ControllerContext.HttpContext.Response.Charset         = "UTF-8";

                    // 文件上传后的保存路径
                    string filePath = Server.MapPath("~/UploadFiles/");
                    DirectoryUtil.AssertDirExist(filePath);

                    string fileName      = Path.GetFileName(fileData.FileName);       //原始文件名称
                    string fileExtension = Path.GetExtension(fileName);               //文件扩展名
                    string saveName      = Guid.NewGuid().ToString() + fileExtension; //保存文件名称

                    FileUploadInfo info = new FileUploadInfo();
                    info.FileData = ReadFileBytes(fileData);
                    if (info.FileData != null)
                    {
                        info.FileSize = info.FileData.Length;
                    }
                    info.Category       = folder;
                    info.FileName       = fileName;
                    info.FileExtend     = fileExtension;
                    info.AttachmentGUID = guid;
                    info.AddTime        = DateTime.Now;
                    info.Editor         = CurrentUser.Name;//登录人
                    //info.Owner_ID = OwerId;//所属主表记录ID

                    result = BLLFactory <FileUpload> .Instance.Upload(info);

                    if (!result.Success)
                    {
                        LogTextHelper.Error("上传文件失败:" + result.ErrorMessage);
                    }
                }
                catch (Exception ex)
                {
                    result.ErrorMessage = ex.Message;
                    LogTextHelper.Error(ex);
                }
            }
            else
            {
                result.ErrorMessage = "fileData对象为空";
            }

            return(ToJsonContent(result));
        }
Beispiel #6
0
        public ActionResult Upload(HttpPostedFileBase fileData, string guid, string folder)
        {
            if (fileData != null)
            {
                try
                {
                    /*ControllerContext.HttpContext.Request.ContentEncoding = Encoding.GetEncoding("UTF-8");
                     * ControllerContext.HttpContext.Response.ContentEncoding = Encoding.GetEncoding("UTF-8");
                     * ControllerContext.HttpContext.Response.Charset = "UTF-8";*/

                    string filePath = Server.MapPath("/UploadFiles");
                    DirectoryUtil.AssertDirExist(filePath);

                    string fileName      = Path.GetFileName(fileData.FileName);
                    string fileExtension = Path.GetExtension(fileName);

                    /*if (fileExtension == "")
                     * {
                     *  fileExtension = " ";
                     * }*/
                    string saveName = Guid.NewGuid().ToString() + fileExtension;

                    FileUpload info = new FileUpload();
                    info.FileData = ReadFileBytes(fileData);
                    if (info.FileData != null)
                    {
                        info.FileSize = info.FileData.Length;
                    }
                    info.Category     = folder;
                    info.FileName     = fileName;
                    info.FileExtend   = fileExtension;
                    info.AttachmentID = guid;
                    info.AddTime      = DateTime.Now;
                    //info.Editor = CurrentUser.Name;

                    CommonResult result = BLLFactory <FileUploadBLL> .Instance.Upload(info);

                    if (!result.Success)
                    {
                        LogTextHelper.Error("上传文件失败:" + result.ErrorMessage);
                    }
                    return(Content(result.Success.ToString()));
                }
                catch (Exception ex)
                {
                    LogTextHelper.Error(ex);
                    return(Content("false"));
                }
            }
            else
            {
                return(Content("false"));
            }
        }
Beispiel #7
0
        private void btnDownload_Click(object sender, EventArgs e)
        {
            if (this.listView1.CheckedItems.Count == 0)
            {
                MessageDxUtil.ShowTips("请勾选下载的文件!");
                return;
            }

            string path = FileDialogHelper.OpenDir();

            if (!string.IsNullOrEmpty(path))
            {
                DirectoryUtil.AssertDirExist(Path.GetDirectoryName(path));

                #region  载保存图片
                bool hasError = false;

                foreach (ListViewItem item in this.listView1.CheckedItems)
                {
                    if (item != null && item.Tag != null)
                    {
                        string id = item.Tag.ToString();

                        try
                        {
                            FileUploadInfo fileInfo = BLLFactory <FileUpload> .Instance.Download(id);

                            if (fileInfo != null && fileInfo.FileData != null)
                            {
                                string filePath = Path.Combine(path, fileInfo.FileName);
                                FileUtil.CreateFile(filePath, fileInfo.FileData);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogTextHelper.Error(ex);
                            hasError = true;
                        }
                    }
                }
                #endregion

                if (hasError)
                {
                    MessageDxUtil.ShowError("保存文件出现错误。具体请查看日志文件!");
                }
                else
                {
                    System.Diagnostics.Process.Start(path);
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// 调用AsposeCell控件,生成Excel文件
        /// </summary>
        /// <param name="datatable">生成的表格数据</param>
        /// <param name="relatedPath">服务器相对路径</param>
        /// <returns></returns>
        protected virtual bool GenerateExcel(DataTable datatable, string relatedPath)
        {
            #region 把DataTable转换为Excel并输出
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //为单元格添加样式
            Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
            //设置居中
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            //设置背景颜色
            style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
            style.Pattern         = Aspose.Cells.BackgroundType.Solid;
            style.Font.IsBold     = true;

            int rowIndex = 0;
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                DataColumn col        = datatable.Columns[i];
                string     columnName = col.Caption ?? col.ColumnName;
                workbook.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
                workbook.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
            }
            rowIndex++;

            foreach (DataRow row in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    workbook.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
                }
                rowIndex++;
            }

            for (int k = 0; k < datatable.Columns.Count; k++)
            {
                workbook.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            workbook.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);

            //根据用户创建目录,确保生成的文件不会产生冲突
            string realPath   = Server.MapPath(relatedPath);
            string parentPath = Directory.GetParent(realPath).FullName;
            DirectoryUtil.AssertDirExist(parentPath);

            workbook.Save(realPath, Aspose.Cells.SaveFormat.Excel97To2003);

            #endregion

            return(true);
        }
Beispiel #9
0
        /// <summary>
        /// 删除物理文件
        /// </summary>
        /// <param name="info">文件信息</param>
        private void DeleteFile(FileUploadInfo info)
        {
            try
            {
                if (info != null && !string.IsNullOrEmpty(info.SavePath))
                {
                    if (info.BasePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                    {
                    }
                    else if (info.BasePath.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
                    {
                    }
                    else
                    {
                        //普通文件删除操作
                        string serverRealPath = PathCombine(info.BasePath, info.SavePath.Replace('\\', '/'));
                        if (!IsPhysicalPath(serverRealPath))
                        {
                            //如果是相对目录,加上当前程序的目录才能定位文件地址
                            serverRealPath = PathCombine(System.AppDomain.CurrentDomain.BaseDirectory, serverRealPath);

                            //如果是相对目录的,移动到删除目录里面
                            if (File.Exists(serverRealPath))
                            {
                                try
                                {
                                    string deletedPath = PathCombine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine(info.BasePath, "DeletedFiles"));
                                    DirectoryUtil.AssertDirExist(deletedPath);

                                    string newFilePath = PathCombine(deletedPath, info.FileName);
                                    newFilePath = GetRightFileName(newFilePath, 1);
                                    File.Move(serverRealPath, newFilePath);
                                }
                                catch (Exception ex)
                                {
                                    LogTextHelper.Error(ex);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //记录删除操作错误
                LogHelper.Error(ex);
            }
        }
Beispiel #10
0
        /// <summary>
        /// 根据属性配置自动保存图片
        /// </summary>
        public void AutoCaptureScreen()
        {
            DirectoryUtil.AssertDirExist(this.ImageSavePath);
            if (DirectoryUtil.IsExistDirectory(this.ImageSavePath))
            {
                string SubPath = Path.Combine(this.ImageSavePath, DateTimeHelper.GetServerDate());
                DirectoryUtil.CreateDirectory(SubPath);

                DateTime snapTime     = DateTimeHelper.GetServerDateTime2();
                string   baseFilename = snapTime.ToString("yyyy_MM_dd-HH_mm_ss");
                string   fullFilename = Path.Combine(SubPath, baseFilename);
                if (!string.IsNullOrEmpty(this.ImageExtension.Trim('.')))
                {
                    fullFilename += "." + this.ImageExtension.Trim('.');
                }
                else
                {
                    fullFilename += "." + this.ImageFormat.ToString();
                }
                CaptureScreenToFile(fullFilename, ImageFormat);
            }
        }
Beispiel #11
0
        /// <summary>
        /// 根据选中的ID记录,生成对应的PDF报表,返回路径
        /// </summary>
        /// <param name="ids">选中的ID记录,逗号分开</param>
        /// <returns></returns>
        public ActionResult ExportPdf(string ids)
        {
            ActionResult result = Content("");

            if (!string.IsNullOrEmpty(ids))
            {
                //利用接口获取列表数据
                var list = BLLFactory <Asset> .Instance.FindByIDs(ids);

                //报表文件路径
                string reportPath = "/Report/barcode2.frx";
                //转换为物理路径
                reportPath = Server.MapPath(reportPath);

                //导出PDF的文件路径
                string exportPdfPath = string.Format("/GenerateFiles/{0}/AssetReport.pdf", CurrentUser.Name);
                //转换为物理路径
                string realPath = Server.MapPath(exportPdfPath);
                //确保目录生成
                string parentPath = Directory.GetParent(realPath).FullName;
                DirectoryUtil.AssertDirExist(parentPath);

                //生成PDF报表文档到具体文件
                Report report = new Report();
                report.Load(reportPath);

                //定义参数和数据格式
                var dict = new Dictionary <string, object>();
                var dt   = DataTableHelper.CreateTable("ID,Name,CurrDept,Code,UsePerson,KeepAddr");
                if (list != null)
                {
                    foreach (var info in list)
                    {
                        var dr = dt.NewRow();
                        dr["ID"]        = info.ID;
                        dr["Name"]      = info.Name;
                        dr["CurrDept"]  = info.CurrDept;
                        dr["Code"]      = info.Code;
                        dr["UsePerson"] = info.UsePerson;
                        dr["KeepAddr"]  = info.KeepAddr;
                        dt.Rows.Add(dr);
                    }
                }

                //刷新数据源
                foreach (string key in dict.Keys)
                {
                    report.SetParameterValue(key, dict[key]);
                }
                report.RegisterData(dt, "T_Asset");

                //运行报表
                report.Prepare();

                //导出PDF报表
                PDFExport export = new PDFExport();
                report.Export(export, realPath);
                report.Dispose();

                if (System.IO.File.Exists(realPath))
                {
                    result = Content(exportPdfPath);//返回Web相对路径
                }
            }
            return(result);
        }
        /// <summary>
        /// 根据查询条件导出列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            #region 根据参数获取List列表
            string where = GetPagerCondition();
            string CustomedCondition     = Request["CustomedCondition"] ?? "";
            List <AddressGroupInfo> list = new List <AddressGroupInfo>();

            if (!string.IsNullOrWhiteSpace(CustomedCondition))
            {
                //如果为自定义的json参数列表,那么可以使用字典反序列化获取参数,然后处理
                //Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(CustomedCondition);

                //如果是条件的自定义,可以使用Find查找
                list = baseBLL.Find(CustomedCondition);
            }
            else
            {
                list = baseBLL.Find(where);
            }

            #endregion

            #region 把列表转换为DataTable
            DataTable datatable = DataTableHelper.CreateTable("序号|int," + columnString);
            DataRow   dr;
            int       j = 1;
            for (int i = 0; i < list.Count; i++)
            {
                dr                 = datatable.NewRow();
                dr["序号"]           = j++;
                dr["父ID"]          = list[i].PID;
                dr["通讯录类型[个人,公司]"] = list[i].AddressType;
                dr["分组名称"]         = list[i].Name;
                dr["备注"]           = list[i].Note;
                dr["排序序号"]         = list[i].Seq;
                dr["创建人"]          = list[i].Creator;
                dr["创建时间"]         = list[i].CreateTime;
                //如果为外键,可以在这里进行转义,如下例子
                //dr["客户名称"] = BLLFactory<Customer>.Instance.GetCustomerName(list[i].Customer_ID);//转义为客户名称

                datatable.Rows.Add(dr);
            }
            #endregion

            #region 把DataTable转换为Excel并输出
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //为单元格添加样式
            Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
            //设置居中
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            //设置背景颜色
            style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
            style.Pattern         = BackgroundType.Solid;
            style.Font.IsBold     = true;

            int rowIndex = 0;
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                DataColumn col        = datatable.Columns[i];
                string     columnName = col.Caption ?? col.ColumnName;
                workbook.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
                workbook.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
            }
            rowIndex++;

            foreach (DataRow row in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    workbook.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
                }
                rowIndex++;
            }

            for (int k = 0; k < datatable.Columns.Count; k++)
            {
                workbook.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            workbook.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);

            //根据用户创建目录,确保生成的文件不会产生冲突
            string filePath   = string.Format("/GenerateFiles/{0}/AddressGroup.xls", CurrentUser.Name);
            string realPath   = Server.MapPath(filePath);
            string parentPath = Directory.GetParent(realPath).FullName;
            DirectoryUtil.AssertDirExist(parentPath);

            workbook.Save(realPath, Aspose.Cells.SaveFormat.Excel97To2003);

            #endregion

            //返回生成后的文件路径,让客户端根据地址下载
            return(Content(filePath));
        }
Beispiel #13
0
        /// <summary>
        /// 对附件组包含的文件进行归档处理,归档文件重新移动到指定的归档目录中
        /// </summary>
        /// <param name="attachmentGUID">附件组GUID</param>
        /// <param name="basePath">基础路径</param>
        /// <param name="archiveCategory">归档目录</param>
        /// <returns></returns>
        public CommonResult ArchiveFile(string attachmentGUID, string basePath, string archiveCategory)
        {
            var result = new CommonResult();

            if (string.IsNullOrEmpty(basePath))
            {
                result.ErrorMessage = "基础路径basePath没有指定,无法归档";
                return(result);
            }

            var fileList = BLLFactory <FileUpload> .Instance.GetByAttachGUID(attachmentGUID);

            foreach (var info in fileList)
            {
                if (info != null && !string.IsNullOrEmpty(info.SavePath))
                {
                    if (!string.IsNullOrEmpty(info.BasePath))
                    {
                        var url = info.BasePath.UriCombine(info.SavePath);
                        if (info.BasePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
                        {
                            result.ErrorMessage = "HTTP路径文件无法归档";
                        }
                        else if (info.BasePath.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
                        {
                            result.ErrorMessage = "FTP路径文件无法归档";
                        }
                        else
                        {
                            //相对目录或者本地目录可以归档

                            //归档实际路径
                            string realArchiveBaseDir = basePath;
                            if (!IsPhysicalPath(realArchiveBaseDir))
                            {
                                //如果没指定基础路径,则以配置为主,如果没有配置项AttachmentBasePath,默认一个相对目录
                                string AttachmentBasePath = config.AppConfigGet("AttachmentBasePath");//配置的基础路径
                                if (string.IsNullOrEmpty(AttachmentBasePath))
                                {
                                    //默认以根目录下的UploadFiles目录为上传目录, 例如"C:\SPDTPatientMisService\UploadFiles";
                                    AttachmentBasePath = AppDomain.CurrentDomain.BaseDirectory.PathCombine("UploadFiles");
                                }
                                //和附件上传目录,组合为一个正确路径
                                realArchiveBaseDir = AttachmentBasePath.PathCombine(realArchiveBaseDir);
                            }
                            //包含分类目录的路径
                            string realArchivePath = realArchiveBaseDir.PathCombine(archiveCategory);

                            //实际文件路径
                            string serverRealPath = PathCombine(info.BasePath, info.SavePath.Replace('\\', '/'));
                            if (!IsPhysicalPath(serverRealPath))
                            {
                                //如果是相对目录,加上当前程序的目录才能定位文件地址
                                serverRealPath = AppDomain.CurrentDomain.BaseDirectory.PathCombine(serverRealPath);
                            }

                            try
                            {
                                //确保移动的目录存在,不存在则创建
                                DirectoryUtil.AssertDirExist(realArchivePath);
                                //移动后的路径
                                var movedFilePath = realArchivePath.PathCombine(info.FileName);

                                if (File.Exists(serverRealPath) && !File.Exists(movedFilePath))
                                {
                                    //移动文件
                                    File.Move(serverRealPath, movedFilePath);

                                    //修改数据库的文件路径并更新
                                    string    filePath = movedFilePath.Replace(realArchiveBaseDir, "");
                                    Hashtable ht       = new Hashtable();
                                    ht.Add("BasePath", realArchiveBaseDir);
                                    ht.Add("SavePath", filePath);
                                    baseDal.UpdateFields(ht, info.ID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var tips = "文件归档出现错误:" + ex.Message;
                                LogTextHelper.Error(tips);
                                result.ErrorMessage = tips;
                            }
                        }
                    }
                }
            }
            result.Success = true;

            return(result);
        }
Beispiel #14
0
        /// <summary>
        /// 根据查询条件导出列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            #region 根据参数获取List列表
            string where = GetPagerCondition();
            string CustomedCondition     = Request["CustomedCondition"] ?? "";
            List <DaClientInfoInfo> list = new List <DaClientInfoInfo>();

            if (!string.IsNullOrWhiteSpace(CustomedCondition))
            {
                //如果为自定义的json参数列表,那么可以使用字典反序列化获取参数,然后处理
                //Dictionary<string, string> dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(CustomedCondition);

                //如果是条件的自定义,可以使用Find查找
                list = baseBLL.Find(CustomedCondition);
            }
            else
            {
                list = baseBLL.Find(where);
            }

            #endregion

            #region 把列表转换为DataTable
            DataTable datatable = DataTableHelper.CreateTable("序号|int," + columnString);
            DataRow   dr;
            int       j = 1;
            for (int i = 0; i < list.Count; i++)
            {
                dr           = datatable.NewRow();
                dr["序号"]     = j++;
                dr["Zhh"]    = list[i].Zhh;
                dr["Qy"]     = list[i].Qy;
                dr["Sh"]     = list[i].Sh;
                dr["Cbbh"]   = list[i].Cbbh;
                dr["Bxh"]    = list[i].Bxh;
                dr["Hmcm"]   = list[i].Hmcm;
                dr["Dzcm"]   = list[i].Dzcm;
                dr["Dhhm"]   = list[i].Dhhm;
                dr["Mobile"] = list[i].Mobile;
                dr["Lxr"]    = list[i].Lxr;
                dr["Hth"]    = list[i].Hth;
                dr["Hm"]     = list[i].Hm;
                dr["Dw"]     = list[i].Dw;
                dr["Dwdh"]   = list[i].Dwdh;
                dr["Dz"]     = list[i].Dz;
                dr["Yhxz"]   = list[i].Yhxz;
                dr["Sffs"]   = list[i].Sffs;
                dr["Sfzh"]   = list[i].Sfzh;
                dr["Ysxz"]   = list[i].Ysxz;
                dr["Jhrq"]   = list[i].Jhrq;
                dr["Xhrq"]   = list[i].Xhrq;
                dr["Yjsl"]   = list[i].Yjsl;
                dr["Yhzt"]   = list[i].Yhzt;
                dr["Gh"]     = list[i].Gh;
                dr["Rks"]    = list[i].Rks;
                dr["Fphm"]   = list[i].Fphm;
                dr["Fpdz"]   = list[i].Fpdz;
                dr["Fkdwqc"] = list[i].Fkdwqc;
                dr["Fkdwzh"] = list[i].Fkdwzh;
                dr["Fkkhyh"] = list[i].Fkkhyh;
                dr["Yhlx"]   = list[i].Yhlx;
                dr["Cby"]    = list[i].Cby;
                //如果为外键,可以在这里进行转义,如下例子
                //dr["客户名称"] = BLLFactory<Customer>.Instance.GetCustomerName(list[i].Customer_ID);//转义为客户名称

                datatable.Rows.Add(dr);
            }
            #endregion

            #region 把DataTable转换为Excel并输出
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //为单元格添加样式
            Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
            //设置居中
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            //设置背景颜色
            style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
            style.Pattern         = BackgroundType.Solid;
            style.Font.IsBold     = true;

            int rowIndex = 0;
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                DataColumn col        = datatable.Columns[i];
                string     columnName = col.Caption ?? col.ColumnName;
                workbook.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
                workbook.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
            }
            rowIndex++;

            foreach (DataRow row in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    workbook.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
                }
                rowIndex++;
            }

            for (int k = 0; k < datatable.Columns.Count; k++)
            {
                workbook.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            workbook.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);

            //根据用户创建目录,确保生成的文件不会产生冲突
            string filePath   = string.Format("/GenerateFiles/{0}/DaClientInfo.xls", CurrentUser.Name);
            string realPath   = Server.MapPath(filePath);
            string parentPath = Directory.GetParent(realPath).FullName;
            DirectoryUtil.AssertDirExist(parentPath);

            workbook.Save(realPath, Aspose.Cells.SaveFormat.Excel97To2003);

            #endregion

            //返回生成后的文件路径,让客户端根据地址下载
            return(Content(filePath));
        }
        /// <summary>
        /// 根据查询条件导出列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult Export()
        {
            #region 根据参数获取List列表
            string where = GetPagerCondition();
            string             CustomedCondition = Request["CustomedCondition"] ?? "";
            List <ContactInfo> list = new List <ContactInfo>();

            if (!string.IsNullOrWhiteSpace(CustomedCondition))
            {
                Dictionary <string, string> dict = JsonConvert.DeserializeObject <Dictionary <string, string> >(CustomedCondition);
                if (dict != null)
                {
                    string id        = dict["id"];
                    string groupname = dict["groupname"];
                    string userid    = dict["userid"];

                    if (string.IsNullOrEmpty(id))
                    {
                        if (groupname == "所有联系人")
                        {
                            where = "";//直接使用空条件
                            list  = baseBLL.Find(where);
                        }
                        else if (groupname == "未分组联系人")
                        {
                            list = BLLFactory <Contact> .Instance.FindByGroupName(userid, null);
                        }
                    }
                    else
                    {
                        list = BLLFactory <Contact> .Instance.FindByGroupName(userid, groupname);
                    }
                }
            }
            else
            {
                list = baseBLL.Find(where);
            }
            #endregion

            #region 把列表转换为DataTable
            DataTable datatable = DataTableHelper.CreateTable("序号|int," + columnString);
            DataRow   dr;
            int       j = 1;
            for (int i = 0; i < list.Count; i++)
            {
                dr         = datatable.NewRow();
                dr["序号"]   = j++;
                dr["客户名称"] = BLLFactory <Customer> .Instance.GetCustomerName(list[i].Customer_ID);//转义为客户名称

                dr["编号"]    = list[i].HandNo;
                dr["姓名"]    = list[i].Name;
                dr["身份证号码"] = list[i].IDCarNo;
                dr["出生日期"]  = list[i].Birthday;
                dr["性别"]    = list[i].Sex;
                dr["办公电话"]  = list[i].OfficePhone;
                dr["家庭电话"]  = list[i].HomePhone;
                dr["传真"]    = list[i].Fax;
                dr["联系人手机"] = list[i].Mobile;
                dr["联系人地址"] = list[i].Address;
                dr["邮政编码"]  = list[i].ZipCode;
                dr["电子邮件"]  = list[i].Email;
                dr["QQ号码"]  = list[i].Qq;
                dr["备注"]    = list[i].Note;
                dr["排序序号"]  = list[i].Seq;
                dr["所在省份"]  = list[i].Province;
                dr["城市"]    = list[i].City;
                dr["所在行政区"] = list[i].District;
                dr["籍贯"]    = list[i].Hometown;
                dr["家庭住址"]  = list[i].HomeAddress;
                dr["民族"]    = list[i].Nationality;
                dr["教育程度"]  = list[i].Eduction;
                dr["毕业学校"]  = list[i].GraduateSchool;
                dr["政治面貌"]  = list[i].Political;
                dr["职业类型"]  = list[i].JobType;
                dr["职称"]    = list[i].Titles;
                dr["职务"]    = list[i].Rank;
                dr["所在部门"]  = list[i].Department;
                dr["爱好"]    = list[i].Hobby;
                dr["属相"]    = list[i].Animal;
                dr["星座"]    = list[i].Constellation;
                dr["婚姻状态"]  = list[i].MarriageStatus;
                dr["健康状况"]  = list[i].HealthCondition;
                dr["重要级别"]  = list[i].Importance;
                dr["认可程度"]  = list[i].Recognition;
                dr["关系"]    = list[i].RelationShip;
                dr["负责需求"]  = list[i].ResponseDemand;
                dr["关心重点"]  = list[i].CareFocus;
                dr["利益诉求"]  = list[i].InterestDemand;
                dr["体型"]    = list[i].BodyType;
                dr["吸烟"]    = list[i].Smoking;
                dr["喝酒"]    = list[i].Drink;
                dr["身高"]    = list[i].Height;
                dr["体重"]    = list[i].Weight;
                dr["视力"]    = list[i].Vision;
                dr["个人简述"]  = list[i].Introduce;

                datatable.Rows.Add(dr);
            }
            #endregion

            #region 把DataTable转换为Excel并输出
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            //为单元格添加样式
            Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
            //设置居中
            style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;
            //设置背景颜色
            style.ForegroundColor = System.Drawing.Color.FromArgb(153, 204, 0);
            style.Pattern         = BackgroundType.Solid;
            style.Font.IsBold     = true;

            int rowIndex = 0;
            for (int i = 0; i < datatable.Columns.Count; i++)
            {
                DataColumn col        = datatable.Columns[i];
                string     columnName = col.Caption ?? col.ColumnName;
                workbook.Worksheets[0].Cells[rowIndex, i].PutValue(columnName);
                workbook.Worksheets[0].Cells[rowIndex, i].SetStyle(style);
            }
            rowIndex++;

            foreach (DataRow row in datatable.Rows)
            {
                for (int i = 0; i < datatable.Columns.Count; i++)
                {
                    workbook.Worksheets[0].Cells[rowIndex, i].PutValue(row[i].ToString());
                }
                rowIndex++;
            }

            for (int k = 0; k < datatable.Columns.Count; k++)
            {
                workbook.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            workbook.Worksheets[0].FreezePanes(1, 0, 1, datatable.Columns.Count);

            //根据用户创建目录,确保生成的文件不会产生冲突
            string filePath   = string.Format("/GenerateFiles/{0}/Contact.xls", CurrentUser.Name);
            string realPath   = Server.MapPath(filePath);
            string parentPath = Directory.GetParent(realPath).FullName;
            DirectoryUtil.AssertDirExist(parentPath);

            workbook.Save(realPath, Aspose.Cells.SaveFormat.Excel97To2003);

            #endregion

            //返回生成后的文件路径,让客户端根据地址下载
            return(Content(filePath));
        }