private void SimpleButton1_Click(object sender, EventArgs e)
        {
            var dialog = new XtraSaveFileDialog
            {
                DefaultExt       = "pdf",
                FileName         = textEditFinalFileName.Text,
                InitialDirectory = "D://"
            };
            // 显示文件保存对话框
            var dialogResult = dialog.ShowDialog();

            // 用户取消
            if (dialogResult != DialogResult.OK)
            {
                return;
            }

            // 生成PDF
            _envelopeResponse.GeneratePdfFile(dialog.FileName, _orderResponse.Urgent, textEditFinalMark.Text, processValue =>
            {
                RefreshProgress(processValue);
                Application.DoEvents();
            }, message => { XtraMessageBox.Show(message); });

            if (checkEdit1.Checked)
            {
                System.Diagnostics.Process.Start("Explorer.exe", "\"" + dialog.FileName + "\"");
            }

            DialogResult = DialogResult.OK;
        }
Exemple #2
0
        private async void SimpleButtonCreatePackageOnClick(object sender, EventArgs e)
        {
            try
            {
                using (var saveDialog = new XtraSaveFileDialog())
                {
                    saveDialog.Title  = "Please select a location to save the package";
                    saveDialog.Filter = "WolvenKit Package File | *.wkp";
                    if (saveDialog.ShowDialog() == DialogResult.OK)
                    {
                        var isSuccessful = await CreatePackage(saveDialog.FileName);

                        if (isSuccessful)
                        {
                            XtraMessageBox.Show($"Package {saveDialog.FileName} Has Been Successfully Created!",
                                                "Package Created", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {
                            XtraMessageBox.Show(
                                "An error occurred creating the package. Review the log / output window for details.",
                                "Error Creating The Package", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"Error Creating The Package: \n\n {ex}", "Error Creating Package",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #3
0
 private void btnExcel_ItemClick(object sender, ItemClickEventArgs e)
 {
     if (DataVJ.Columns.Count > 5)
     {
         XtraSaveFileDialog sfd = new XtraSaveFileDialog();
         sfd.Title            = "Save text Files";
         sfd.DefaultExt       = "xlsx";
         sfd.Filter           = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
         sfd.FilterIndex      = 1;
         sfd.RestoreDirectory = true;
         sfd.FileName         = $"{_Name} {((DateTime)eDate1.EditValue).ToString("ddMMyy")}.xlsx";
         if (sfd.ShowDialog() == DialogResult.OK)
         {
             using (ExcelPackage pck = new ExcelPackage(new FileInfo(sfd.FileName)))
             {
                 ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
                 ws.Cells["A1"].LoadFromDataTable(DataVJ, PrintHeaders: true);
                 for (var col = 1; col < DataVJ.Columns.Count + 1; col++)
                 {
                     if (DataVJ.Columns[col - 1].DataType == typeof(double))    //col number 2 is equivalent to column B
                     {
                         ws.Column(col).Style.Numberformat.Format = "#,##0.00"; //apply the number formatting you need
                         ws.Column(col).AutoFit();
                     }
                 }
                 var ms = new MemoryStream();
                 pck.Save();
                 XtraMessageBox.Show("Xong", "Thông báo");
             }
         }
     }
 }
Exemple #4
0
        private void xuat(object sender, EventArgs e)
        {
            XtraSaveFileDialog SaveFileDialog = new XtraSaveFileDialog();

            SaveFileDialog.ShowDialog();

            gvKhoHang.ExportToXlsx(SaveFileDialog.FileName + ".xlsx");
        }
        private void btnXuat_Click(object sender, EventArgs e)
        {
            XtraSaveFileDialog SaveFileDialog = new XtraSaveFileDialog();

            SaveFileDialog.ShowDialog();

            gcDSPT.ExportToXlsx(SaveFileDialog.FileName + ".xlsx");
        }
Exemple #6
0
 public static string GetFileNameViaSavePrompt(string extension, string filters)
 {
     using (var dialog = new XtraSaveFileDialog())
     {
         dialog.Filter     = filters;
         dialog.DefaultExt = extension;
         return(dialog.ShowDialog() == DialogResult.OK ? dialog.FileName : string.Empty);
     }
 }
        private void DescargarPlantilla()
        {
            try
            {
                using (var dialogoParaGuardar = new XtraSaveFileDialog())
                {
                    dialogoParaGuardar.Title            = "Guardar en...";
                    dialogoParaGuardar.Filter           = @"Archivos de excel (*.xlsx)|*.xlsx";
                    dialogoParaGuardar.FilterIndex      = 2;
                    dialogoParaGuardar.RestoreDirectory = true;

                    if (dialogoParaGuardar.ShowDialog() != DialogResult.OK)
                    {
                        return;
                    }

                    var libroDeTrabajo        = new XLWorkbook();
                    var WorkSheetNombre       = "Familia";
                    var parametroUseSubFamily = Parametros.FirstOrDefault(p => p.PARAMETER_ID == Enums.GetStringValue(IdParametro.UseMaterialSubFamily) && p.GROUP_ID == Enums.GetStringValue(GrupoParametro.MaterialSubFamily));
                    if (parametroUseSubFamily != null && int.Parse(parametroUseSubFamily.VALUE) == (int)SiNo.Si)
                    {
                        WorkSheetNombre = "Sub-familia";
                    }
                    var hoja = libroDeTrabajo.Worksheets.Add(WorkSheetNombre);

                    GenerarHojaDeClase(hoja, 1, 1, 5);

                    if (File.Exists(dialogoParaGuardar.FileName))
                    {
                        File.Delete(dialogoParaGuardar.FileName);
                    }

                    libroDeTrabajo.SaveAs(dialogoParaGuardar.FileName);



                    XtraMessageBoxArgs args = new XtraMessageBoxArgs();
                    args.AutoCloseOptions.Delay = 3000;
                    args.Caption            = "Operación exitosa";
                    args.Text               = "Archivo generado exitósamente, ¿Desea abrir el archivo?";
                    args.Buttons            = new[] { DialogResult.Yes, DialogResult.No };
                    args.Icon               = System.Drawing.SystemIcons.Question;
                    args.DefaultButtonIndex = 0;
                    args.AutoCloseOptions.ShowTimerOnDefaultButton = true;
                    if (XtraMessageBox.Show(args) == DialogResult.Yes)
                    {
                        Process.Start(dialogoParaGuardar.FileName);
                    }
                }
            }
            catch (Exception e)
            {
                InteraccionConUsuarioServicio.Alerta($"Error al descargar la plantilla: {e.Message}");
            }
        }
 private void btnBackup_ItemClick(object sender, ItemClickEventArgs e)
 {
     using (XtraSaveFileDialog saveFileDialog = new XtraSaveFileDialog())
     {
         saveFileDialog.FileName         = string.Format("backup_{0}.bak", DateTime.Now.ToString("ddMMyyy_hhmmss"));
         saveFileDialog.InitialDirectory = Application.StartupPath + "\\data\\backup";
         if (saveFileDialog.ShowDialog() == DialogResult.OK)
         {
             new fBackup(saveFileDialog.FileName).ShowDialog();
         }
     }
 }
Exemple #9
0
        private void btSaveAs_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraSaveFileDialog dlg = new XtraSaveFileDialog();

            dlg.Filter = DataHelper.planFileFilter;
            dlg.ShowDialog();
            if (dlg.FileName != null)
            {
                filePath       = dlg.FileName;
                btSave.Enabled = true;
                DataHelper.SavePlan(plan, filePath);
            }
        }
Exemple #10
0
        public static void initSaveFile(string strDefaulteFileName, string strFilter, string strDefaultExt, Action <string> oActionCallback)
        {
            var saveFileDialog = new XtraSaveFileDialog();

            saveFileDialog.Filter       = strFilter;           //设置文件类型
            saveFileDialog.FileName     = strDefaulteFileName; //设置默认文件名
            saveFileDialog.DefaultExt   = strDefaultExt;       //设置默认格式(可以不设)
            saveFileDialog.AddExtension = true;                //设置自动在文件名中添加扩展名
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                oActionCallback(saveFileDialog.FileName);
            }
        }
Exemple #11
0
        public static string Show()
        {
            XtraSaveFileDialog xsfd = new XtraSaveFileDialog();

            xsfd.Filter = "Excel文件(*.xlsx)|.xlsx";
            DialogResult dr = xsfd.ShowDialog();

            if (dr == DialogResult.OK)
            {
                return(xsfd.FileName);
            }
            return(null);
        }
Exemple #12
0
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            XtraOpenFileDialog Opendlg;
            XtraSaveFileDialog Savedlg;

            using (Savedlg = new XtraSaveFileDialog())
            {
                Savedlg.Filter = "EXCEL 파일(*.xlsx)|*.xlsx|All files (*.*)|*.*";

                if (Savedlg.ShowDialog() == DialogResult.OK)
                {
                    Spread1.SaveDocument(Savedlg.FileName);
                }
            }
        }
Exemple #13
0
        public async void SaveQueryDialogAsync(string content)
        {
            var dialog = new XtraSaveFileDialog
            {
                Filter = "SQL Files (*.sql)|*.sql|Text Files(*.txt)|*.txt",
                Title  = "Save Query As "
            };

            var result = dialog.ShowDialog();

            if (result == DialogResult.OK)
            {
                await Task.Run(() => SaveQueryFile(dialog.FileName, content))
                .ContinueWith(x => ShowFileSaveSuccess(x.Result, dialog.FileName), TaskScheduler.FromCurrentSynchronizationContext()).ConfigureAwait(false);
            }
        }
Exemple #14
0
        private DialogResult SaveFileDialogHelper(bool decisionTaken = false)
        {
            if (this.NeedToSave || decisionTaken)
            {
                if (!decisionTaken)
                {
                    this.dialogResult = XtraMessageBox.Show("Save your last modifications?", "Warning", MessageBoxButtons.YesNoCancel);
                }
                else
                {
                    this.dialogResult = DialogResult.Yes;
                }
                switch (this.dialogResult)
                {
                case DialogResult.Yes:
                    XtraSaveFileDialog dialog = this.xtraSaveFileDialog1;
                    dialog.InitialDirectory         = this.DefaultPath;
                    dialog.ShowDragDropConfirmation = true;
                    dialog.Filter          = FILE_FILTERS;
                    dialog.FileName        = this.DefaultFileName;
                    dialog.CreatePrompt    = true;
                    dialog.OverwritePrompt = true;
                    this.dialogResult      = dialog.ShowDialog();
                    if (this.dialogResult == DialogResult.OK)
                    {
                        this.DefaultFileName = Path.GetFileName(dialog.FileName);
                        this.DefaultPath     = Path.GetDirectoryName(dialog.FileName);
                        return(this.dialogResult = DialogResult.OK);
                    }
                    break;

                case DialogResult.No:
                    this.MsgCollXuc.Warn("File '{0}' not saved.", this.DefaultFileName);
                    break;

                case DialogResult.Cancel:
                    this.MsgCollXuc.Warn("Save operation canceled: '{0}'!", this.DefaultFileName);
                    return(this.dialogResult = DialogResult.Cancel);
                }
            }
            //this.NeedToSave = false;
            //this.UpdateFileNameLabel();
            //this.UpdateFileStatusLabel();
            return(this.dialogResult = DialogResult.Ignore);
        }
Exemple #15
0
        private void groupControl2_CustomButtonClick(object sender, DevExpress.XtraBars.Docking2010.BaseButtonEventArgs e)
        {
            if (e.Button.Properties.Caption == "Xem")
            {
                LoadAllData();
            }
            if (e.Button.Properties.Caption == "Xuất")
            {
                XtraSaveFileDialog SaveFileDialog = new XtraSaveFileDialog();
                SaveFileDialog.ShowDialog();

                gcTonKho.ExportToXlsx(SaveFileDialog.FileName + ".xlsx");
            }
            if (e.Button.Properties.Caption == "Đóng")
            {
                this.Close();
            }
        }
Exemple #16
0
        private DialogResult SaveFileDialogHelper(bool decisionTaken = false)
        {
            if (this.NeedToSave || decisionTaken)
            {
                if (!decisionTaken)
                {
                    this.dialogResult = XtraMessageBox.Show("Save your last modifications?", "Warning", MessageBoxButtons.YesNoCancel);
                }
                else
                {
                    this.dialogResult = DialogResult.Yes;
                }
                switch (this.dialogResult)
                {
                case DialogResult.Yes:
                    XtraSaveFileDialog dialog = this.xtraSaveFileDialog1;
                    dialog.InitialDirectory         = this.DefaultPath;
                    dialog.ShowDragDropConfirmation = true;
                    dialog.Filter          = FILE_FILTERS;
                    dialog.FileName        = this.DefaultFileName;
                    dialog.CreatePrompt    = true;
                    dialog.OverwritePrompt = true;
                    this.dialogResult      = dialog.ShowDialog();
                    if (this.dialogResult == DialogResult.OK)
                    {
                        //System.IO.File.WriteAllText( dialog.FileName, this.mainModule.Text );
                        this.DefaultFileName = Path.GetFileName(dialog.FileName);
                        this.DefaultPath     = Path.GetDirectoryName(dialog.FileName);
                        this.UpdateOpenRecentList(dialog.FileName);
                    }
                    break;

                case DialogResult.No:
                    break;

                case DialogResult.Cancel:
                    return(DialogResult.Cancel);
                }
            }
            this.NeedToSave = false;
            this.UpdateFileNameLabel();
            this.UpdateFileStatusLabel();
            return(this.dialogResult = DialogResult.OK);
        }
        public void SaveDocument(string filePath = null)
        {
            if (filePath != null)
            {
                FileName = filePath;
            }

            if (FileName == null)
            {
                using var dlg = new XtraSaveFileDialog()
                      {
                          Filter = FILTER
                      };
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    FileName = dlg.FileName;
                }
            }

            if (FileName == null)
            {
                throw new ArgumentNullException("filePath");
            }

            using var zip = new ZipFile();
            AddToZip(Properties, zip);
            AddToZip(TitlePage, zip);
            AddToZip(Introduction, zip);
            AddToZip(Summary, zip);
            AddToZip(Bibliography, zip);
            if (Sections != null)
            {
                var i = 1;
                foreach (var section in Sections)
                {
                    AddToZip(section, zip, $"Section{i}.xml");
                }
            }
            if (File.Exists(filePath))
            {
                try { File.Delete(filePath); } catch { }
            }
            zip.Save(filePath);
        }
Exemple #18
0
        public static void ExportExcel(GridControl Grc, GridView Grv, string Fin)
        {
            XtraSaveFileDialog sfd = new XtraSaveFileDialog();

            sfd.Title      = "Lưu File";
            sfd.Filter     = "Excel File (*.xlsx) | *.xlsx";
            sfd.DefaultExt = ".xlsx";
            sfd.FileName   = Fin + ".xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsxExportOptionsEx op = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
                Grv.OptionsPrint.AutoWidth = false;
                op.CustomizeCell          += op_CustomizeCell;
                Grc.ExportToXlsx(sfd.FileName);
                if (XtraMessageBox.Show("Xuất excel thành công, mở file ngay!", "Thông Báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    System.Diagnostics.Process.Start(sfd.FileName);
                }
            }
        }
Exemple #19
0
        /// <summary>
        /// 경로명 없는 전달로 경로명 및 폴더를 지정하여 생성한다.
        /// </summary>
        public void Save()
        {
            String savePath;

            //저장할 내용이 없으면 오류
            if (m_dt == null || m_dt.Rows.Count <= 0)
            {
                XtraMessageBox.Show("저장할 내용이 없습니다.", "저장 오류", MessageBoxButtons.OK);

                return;
            }

            XtraSaveFileDialog saveDlg = new XtraSaveFileDialog();

            if (saveDlg.ShowDialog() == DialogResult.OK)
            {
                saveDlg.Filter = "xml 파일 (*.xml)|*.xml|모든파일(*.*)|*.*";
                savePath       = saveDlg.FileName;

                CUtil.SaveToXml(m_dt, Path.GetDirectoryName(savePath), Path.GetFileNameWithoutExtension(savePath));
            }
        }
Exemple #20
0
        private bool TryGetFilepath()
        {
            var succeeded = false;

            if (string.IsNullOrWhiteSpace(_currentFilepath) || !File.Exists(_currentFilepath))
            {
                using (var dlg = new XtraSaveFileDialog())
                {
                    dlg.Filter           = "Finance File (*.fjson)|*.fjson";
                    dlg.RestoreDirectory = true;

                    if (dlg.ShowDialog(this) == DialogResult.OK)
                    {
                        _currentFilepath = dlg.FileName;
                        succeeded        = true;
                    }
                }
            }
            else
            {
                succeeded = true;
            }
            return(succeeded);
        }
Exemple #21
0
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            string downloadFile = "";

            try
            {
                DataRow Dr = gridView1.GetFocusedDataRow();

                if (Dr["DirFlag"].ToString().Trim() == "d")
                {
                    XtraMessageBox.Show("Directory는 Down이 불가해요");
                    return;
                }

                if (Dr["Size"].ToString().Trim() == "0")
                {
                    XtraMessageBox.Show("Size가 0이에요");
                    return;
                }


                string filename = "";


                using (XtraSaveFileDialog saveDlg = new XtraSaveFileDialog())
                {
                    saveDlg.FileName = Dr["Filename"].ToString();

                    saveDlg.ShowDialog();

                    downloadFile = saveDlg.FileName;
                }

                splashScreenManager1.ShowWaitForm();


                filename = string.Format("{0}/{1}", Dr["Uri_Path"], Dr["Filename"]);
                // Get the object used to communicate with the server.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(filename);
                request.Method = WebRequestMethods.Ftp.DownloadFile;

                //// This example assumes the FTP site uses anonymous logon.
                //request.Credentials = new NetworkCredential("anonymous", "*****@*****.**");

                FtpWebResponse response       = (FtpWebResponse)request.GetResponse();
                Stream         responseStream = response.GetResponseStream();

                FileStream targetFileStream = new FileStream(downloadFile, FileMode.Create, FileAccess.Write);
                byte[]     bufferByteArray  = new byte[1024];
                while (true)
                {
                    int byteCount = responseStream.Read(bufferByteArray, 0, bufferByteArray.Length);

                    if (byteCount == 0)
                    {
                        break;
                    }

                    targetFileStream.Write(bufferByteArray, 0, byteCount);
                }



                responseStream.Close();
                targetFileStream.Close();
                response.Close();
                ExtractZip(downloadFile);

                splashScreenManager1.CloseWaitForm();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
                splashScreenManager1.CloseWaitForm();
            }
        }
Exemple #22
0
        public void ExportarVista(GridView vista, bool preguntarSiDeseaAbrirDocumento, ExportarA tipo)
        {
            if (vista.DataSource == null)
            {
                return;
            }
            if (vista.RowCount <= 0)
            {
                return;
            }

            using (var dialogoParaGuardar = new XtraSaveFileDialog())
            {
                dialogoParaGuardar.Title = "Guardar en...";
                switch (tipo)
                {
                case ExportarA.Excel:
                    dialogoParaGuardar.Filter = @"Archivos de excel (*.xlsx)|*.xlsx";
                    break;

                case ExportarA.Pdf:
                    dialogoParaGuardar.Filter = @"Archivos de pdf (*.pdf)";
                    break;

                default:
                    dialogoParaGuardar.Filter = @"Archivos de word (*.docx)|*.docx";
                    break;
                }

                if (dialogoParaGuardar.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                switch (tipo)
                {
                case ExportarA.Excel:
                    vista.ExportToXlsx(dialogoParaGuardar.FileName);
                    break;

                case ExportarA.Pdf:
                    vista.ExportToPdf(dialogoParaGuardar.FileName);
                    break;

                default:
                    vista.ExportToDocx(dialogoParaGuardar.FileName);
                    break;
                }

                if (!preguntarSiDeseaAbrirDocumento)
                {
                    return;
                }
                XtraMessageBoxArgs args = new XtraMessageBoxArgs();
                args.AutoCloseOptions.Delay = 3000;
                args.Caption            = "Documento";
                args.Text               = "¿Desea abrir el documento?";
                args.Buttons            = new[] { DialogResult.Yes, DialogResult.No };
                args.Icon               = System.Drawing.SystemIcons.Question;
                args.DefaultButtonIndex = 1;
                args.AutoCloseOptions.ShowTimerOnDefaultButton = true;
                if (XtraMessageBox.Show(args) == DialogResult.Yes)
                {
                    Process.Start(dialogoParaGuardar.FileName);
                }
            }
        }
        private void barImport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            XtraSaveFileDialog saveFileDialog = new XtraSaveFileDialog();

            saveFileDialog.ShowDialog();
        }
Exemple #24
0
 public static string ShowSaveFileDialog(Form owner, string title, string fileTypes)
 {
     using XtraSaveFileDialog saveFileDialog = new XtraSaveFileDialog { Title = title, Filter = fileTypes };
     return(saveFileDialog.ShowDialog(owner) == DialogResult.OK ? saveFileDialog.FileName : null);
 }
Exemple #25
0
        private void btnLisanOlustur_Click(object sender, EventArgs e)
        {
            SystemInformations info = new SystemInformations();

            DiskDrive drive = info.GetDiskLis().FirstOrDefault(c => c.PartitionName == Application.StartupPath.Substring(0, 2));


            lisans.Id           = Guid.NewGuid();
            lisans.UserName     = txtUserName.Text;
            lisans.Company      = txtCompany.Text;
            lisans.OnlineLisans = toggleSwitch1.IsOn;
            if (checkButton1.Checked)
            {
                lisans.LicenseCount = 1;
            }
            else
            {
                lisans.LicenseCount = Convert.ToInt32(txtLicenseCount.Value);
            }
            for (int i = 0; i < checkedListBoxControl1.Items.Count; i++)
            {
                if (checkedListBoxControl1.Items[i].CheckState == CheckState.Checked)
                {
                    lisans.Modules.Add(new Module
                    {
                        ModuleTypeEnum = (ModuleTypeEnum)i
                    });
                }
            }
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.BaseBoard,
                Info     = JsonConvert.SerializeObject(info.GetBaseBoardInfo())
            });
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.Bios,
                Info     = JsonConvert.SerializeObject(info.GetBiosInfo())
            });
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.Cpu,
                Info     = JsonConvert.SerializeObject(info.GetCpuInfo())
            });
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.Network,
                Info     = JsonConvert.SerializeObject(info.GetNetworkList().FirstOrDefault())
            });
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.DiskDrive,
                Info     = JsonConvert.SerializeObject(drive)
            });
            lisans.SystemInfos.Add(new SystemInfo
            {
                InfoType = SystemInfoEnum.OperatingSystem,
                Info     = JsonConvert.SerializeObject(info.GetOSInfo())
            });
            var json = JsonConvert.SerializeObject(lisans);
            XtraSaveFileDialog dialog = new XtraSaveFileDialog();

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                File.WriteAllText(dialog.FileName, LicenseInformations.Tools.EncrpytionTool.Encrypt(json));
            }
        }
Exemple #26
0
        private void ExportData()
        {
            try
            {
                btnExport.Enabled = false;
                string             pathFileSave = "";
                XtraSaveFileDialog fileSave     = new XtraSaveFileDialog();
                fileSave.Filter = "Excel files (.xlsx)|*.xlsx";
                fileSave.AutoUpdateFilterDescription = true;
                if (fileSave.ShowDialog() == DialogResult.OK)
                {
                    if (!fileSave.FileName.Contains(".xlsx"))
                    {
                        XtraMessageBox.Show("File save phải định dạng .xlsx", "Thông Báo");
                    }
                    else
                    {
                        //System.IO.File.Copy(PathFile, fileSave.FileName, true);
                        pathFileSave = fileSave.FileName;
                    }
                }
                else
                {
                    return;
                }

                //string sLink = Form_Main.URL_API + "/api/IPC247/sp_extension_GetDataByStore?sql_Exec=" + "sp_Get_Product_Export";
                //var json = API.API_GET(sLink);

                //var jsondata = JObject.Parse(json).GetValue("Data");
                //DataTable dt = (DataTable)JsonConvert.DeserializeObject(jsondata.ToString(), (typeof(DataTable)));
                DataTable dt     = SQLHelper.ExecuteDataTable("sp_Get_Product_Export");
                string    Folder = AppDomain.CurrentDomain.BaseDirectory + "/AppData";
                if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "/AppData"))
                {
                    Directory.CreateDirectory(Folder);
                }

                Folder = AppDomain.CurrentDomain.BaseDirectory + string.Format("/AppData/{0}/", DateTime.Now.ToString("yyyyMMdd"));
                if (!Directory.Exists(Folder))
                {
                    Directory.CreateDirectory(Folder);
                }

                #region Xóa File cũ
                System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "/AppData/");
                foreach (System.IO.DirectoryInfo di in dir.GetDirectories())
                {
                    if (di.Name != DateTime.Today.ToString("yyyyMMdd"))
                    {
                        System.IO.Directory.Delete(di.FullName, true);
                    }
                }
                #endregion Xóa File cũ

                string PathFile = Folder + string.Format("/ExportData_{0}.xlsx", DateTime.Now.ToString("ddMMyyyyHHmmss"));
                using (WebClient webClient = new WebClient())
                {
                    webClient.DownloadFile(new Uri(Form_Main.URL_API + "/Uploads/Tmp/template/template.xlsx"), PathFile);
                }

                System.IO.FileInfo fnew = new System.IO.FileInfo(PathFile);
                using (ExcelPackage pck = new ExcelPackage(fnew))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets["Sheet1"];
                    if (ws == null)
                    {
                        ws = pck.Workbook.Worksheets.Add("Sheet1");
                    }
                    ws.Cells["A2"].LoadFromDataTable(dt, false);
                    pck.Save();
                }
                System.IO.File.Copy(PathFile, fileSave.FileName, true);

                if (File.Exists(PathFile))
                {
                    File.Delete(PathFile);
                }
                try
                {
                    Process.Start(fileSave.FileName);
                }
                catch
                {
                    XtraMessageBox.Show("Bạn cần cài đặt Excel để mở file!", "Thông Báo");
                }
                btnExport.Enabled = true;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                API.API_ERRORLOG(new ERRORLOG(Form_Main.IPAddress, "Form_Product", "ExportData()", ex.ToString()));
                btnExport.Enabled = true;
                return;
            }
        }