Esempio n. 1
0
        private string PromptForFileName()
        {
            var dialog = new FileNameDialog();
            var result = dialog.ShowDialog();

            return(result.HasValue && result.Value ? dialog.Input : string.Empty);
        }
Esempio n. 2
0
        public async Task <string> ShowModelNameDialog(string suggestedfileName)
        {
            var nameDialog = new FileNameDialog();
            var tcs        = new TaskCompletionSource <bool>();

            nameDialog.NameTextBox.Text = suggestedfileName;

            void SaveButtonClicked(object s, RoutedEventArgs a)
            {
                _lmainWindow.Value.DialogRegion.Content = null;
                tcs.TrySetResult(true);
            }

            void CancelButtonClicked(object s, RoutedEventArgs a)
            {
                _lmainWindow.Value.DialogRegion.Content = null;
                tcs.TrySetResult(false);
            }

            nameDialog.SaveButton.Click            += SaveButtonClicked;
            nameDialog.CancelButton.Click          += CancelButtonClicked;
            _lmainWindow.Value.DialogRegion.Content = nameDialog;
            bool okButtonClicked = await tcs.Task;

            nameDialog.SaveButton.Click   -= SaveButtonClicked;
            nameDialog.CancelButton.Click -= CancelButtonClicked;
            if (okButtonClicked)
            {
                return(nameDialog.NameTextBox.Text);
            }
            else
            {
                return(String.Empty);
            }
        }
Esempio n. 3
0
 public static void Postfix(FileNameDialog __instance, TMP_InputField ___inputField)
 {
     if (__instance.name == "BlueprintNameDialog")
     {
         ___inputField.onValueChanged.RemoveAllListeners();
         ___inputField.onEndEdit.RemoveAllListeners();
     }
 }
Esempio n. 4
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void ExecuteAsync(object sender, EventArgs e)
        {
            try
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                var item = _dte.SelectedItems.Item(1);
                Helpers.DteHelpers.GetSelectionData(_dte, out var targetFile, out var projectFolderPath, out var projectFullName);
                var targetFolder = Path.GetDirectoryName(targetFile);

                if (string.IsNullOrEmpty(targetFolder) || !Directory.Exists(targetFolder))
                {
                    return;
                }

                var selectedItem    = item as ProjectItem;
                var selectedProject = item as Project;
                var project         = selectedItem?.ContainingProject ?? selectedProject ?? DteHelpers.GetActiveProject(_dte);

                var root           = Directory.GetParent(AureliaHelper.RootFolder).FullName.Replace(@"\", @"\\"); //escape for pregex
                var relativePath   = Regex.Replace(targetFolder, root, "", RegexOptions.IgnoreCase).Substring(1); // remove starting slash
                var fileNameDialog = new FileNameDialog(relativePath)
                {
                    Title       = "Generate Aurelia Item",
                    IsGlobal    = true,
                    PreviewText = "Please enter the name aurelia item to create using Aurelia Conventions"
                };
                var lowerFolder = targetFolder.ToLower();
                fileNameDialog.GlobalChecked(lowerFolder == AureliaHelper.GetResouceDirectory.ToLower() ||
                                             lowerFolder == AureliaHelper.GetAttributesDirectory.ToLower() ||
                                             lowerFolder == AureliaHelper.GetBindingBehaviorsDirectory.ToLower() ||
                                             lowerFolder == AureliaHelper.GetElementsDirectory.ToLower() ||
                                             lowerFolder == AureliaHelper.GetValueConvertersDirectory.ToLower() ||
                                             targetFile.ToLower().Equals(AureliaHelper.ResourceGlobalFile.ToLower()

                                                                         ));

                var dialog = _dte.OpenDialog(fileNameDialog);
                if (!(dialog.ShowDialog() ?? false))
                {
                    return;
                }
                var moduleName   = dialog.Input;
                var aureliaType  = AureliaHelper.ParseModuleName(moduleName);
                var templates    = Template.GetTemplateFilesByType(aureliaType.ToString().ToLower()).ToList();
                var globalFolder = AureliaHelper.GetDirectory(aureliaType);
                targetFolder = dialog.IsGlobal && !string.IsNullOrWhiteSpace(globalFolder) ? globalFolder : targetFolder;

                var filesToOpen = await Task.WhenAll(templates.Select(templateName => Template.GenerateTemplatesAsync(templateName, targetFolder, dialog.Input, dialog.IsGlobal)));

                filesToOpen.ToList().ForEach(fullFileName => VsShellUtilities.OpenDocument(package, fullFileName));
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message);
            }
        }
Esempio n. 5
0
    public void OnClickNewSave()
    {
        FileNameDialog fileNameDialog = (FileNameDialog)KScreenManager.Instance.StartScreen(ScreenPrefabs.Instance.FileNameDialog.gameObject, base.transform.parent.gameObject);

        fileNameDialog.onConfirm = delegate(string filename)
        {
            filename = Path.Combine(SaveLoader.GetSavePrefixAndCreateFolder(), filename);
            Save(filename);
        };
    }
Esempio n. 6
0
        public static FileNameDialog CreateFolderDialog(System.Action <string, FileNameDialog> onConfirm = null)
        {
            string title = Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_FOLDERBLUEPRINT_TITLE);

            FileNameDialog folderDialog = CreateTextDialog(title, true, onConfirm);

            folderDialog.name = "BlueprintsMod_FolderDialog_" + title;

            return(folderDialog);
        }
Esempio n. 7
0
        protected override void OnDragComplete(Vector3 cursorDown, Vector3 cursorUp)
        {
            base.OnDragComplete(cursorDown, cursorUp);

            if (hasFocus)
            {
                Grid.PosToXY(cursorDown, out int x0, out int y0);
                Grid.PosToXY(cursorUp, out int x1, out int y1);

                if (x0 > x1)
                {
                    Util.Swap(ref x0, ref x1);
                }

                if (y0 < y1)
                {
                    Util.Swap(ref y0, ref y1);
                }

                Blueprint blueprint = BlueprintsState.CreateBlueprint(new Vector2I(x0, y0), new Vector2I(x1, y1), this);
                if (blueprint.IsEmpty())
                {
                    PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_EMPTY), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);
                }

                else
                {
                    FileNameDialog blueprintNameDialog = Utilities.CreateBlueprintRenameDialog();
                    SpeedControlScreen.Instance.Pause(false);

                    blueprintNameDialog.onConfirm = delegate(string blueprintName) {
                        blueprint.Rename(blueprintName.Substring(0, blueprintName.Length - 4));
                        SpeedControlScreen.Instance.Unpause(false);

                        blueprintNameDialog.Deactivate();
                        blueprint.Write();
                        PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_CREATED), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);

                        BlueprintsState.LoadedBlueprints.Add(blueprint);
                        BlueprintsState.SelectedBlueprintIndex = BlueprintsState.LoadedBlueprints.Count - 1;
                    };

                    blueprintNameDialog.onCancel = delegate {
                        SpeedControlScreen.Instance.Unpause(false);

                        PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_CANCELLED), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);
                        blueprintNameDialog.Deactivate();
                    };

                    blueprintNameDialog.Activate();
                }
            }
        }
Esempio n. 8
0
        public static FileNameDialog CreateTextDialog(string title)
        {
            FileNameDialog textDialog = Util.KInstantiateUI <FileNameDialog>(ScreenPrefabs.Instance.FileNameDialog.gameObject, GameScreenManager.Instance.GetParent(GameScreenManager.UIRenderTarget.ScreenSpaceOverlay));

            textDialog.name = title; //.displayName?

            //Transform titleTransform = textDialog.transform.Find("Panel")?.Find("Title_BG")?.Find("Title");
            //if (titleTransform != null && titleTransform.GetComponent<LocText>() != null)
            //    titleTransform.GetComponent<LocText>().text = title;

            return(textDialog);
        }
Esempio n. 9
0
        protected override void OnDragComplete(Vector3 cursorDown, Vector3 cursorUp)
        {
            base.OnDragComplete(cursorDown, cursorUp);

            if (hasFocus)
            {
                Grid.PosToXY(cursorDown, out int x0, out int y0);
                Grid.PosToXY(cursorUp, out int x1, out int y1);

                if (x0 > x1)
                {
                    Util.Swap(ref x0, ref x1);
                }

                if (y0 < y1)
                {
                    Util.Swap(ref y0, ref y1);
                }

                Blueprint blueprint = BlueprintsState.CreateBlueprint(new Vector2I(x0, y0), new Vector2I(x1, y1), this);
                if (blueprint.IsEmpty())
                {
                    PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_EMPTY), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);
                }

                else
                {
                    void onConfirmDelegate(string blueprintName, FileNameDialog parent)
                    {
                        blueprint.Rename(blueprintName, false);
                        blueprint.SetFolder("");

                        SpeedControlScreen.Instance.Unpause(false);

                        PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_CREATED), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);
                        parent.Deactivate();
                    }

                    FileNameDialog blueprintNameDialog = UIUtilities.CreateTextDialog(Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_NAMEBLUEPRINT_TITLE), false, onConfirmDelegate);
                    SpeedControlScreen.Instance.Pause(false);

                    blueprintNameDialog.onCancel = delegate {
                        SpeedControlScreen.Instance.Unpause(false);

                        PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, Strings.Get(BlueprintsStrings.STRING_BLUEPRINTS_CREATE_CANCELLED), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.BLUEPRINTS_CONFIG_FXTIME);
                        blueprintNameDialog.Deactivate();
                    };

                    blueprintNameDialog.Activate();
                }
            }
        }
        private void btnImportEmpsInfo_Click(object sender, EventArgs e)
        {
            btnViewTheUncertaiRecordInExcel.Enabled = false;
            lblResult.Text      = "";
            lblResult.BackColor = this.BackColor;
            lblResult.Visible   = false;
            //判断是否存在Excel进程.
            if (CmdHelper.ifExistsTheProcessByName("EXCEL"))
            {
                FrmPrompt frmPrompt = new FrmPrompt();
                frmPrompt.ShowDialog();
            }
            _uncertainWSPath    = _defaultDir + "\\uncertainRecord_" + TimeHelper.getCurrentTimeStr() + ".xls";
            dgv.DataSource      = null;
            lblResult.Visible   = false;
            lblResult.Text      = "";
            lblResult.BackColor = this.BackColor;
            tb.Clear();
            randomStr   = TimeHelper.getCurrentTimeStr();
            xlsFilePath = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择考勤记录:", "*.xls|*.xls", defaultDir);
            string dir = DirectoryHelper.getDirOfFile(xlsFilePath);

            if (string.IsNullOrEmpty(dir))
            {
                return;
            }
            List <string> xlsFileList = DirectoryHelper.getXlsFileUnderThePrescribedDir(dir);

            xlsFilePathList = new List <string>();
            foreach (string xlsFile in xlsFileList)
            {
                string fileName = DirectoryHelper.getFileNameWithoutSuffix(xlsFile);
                if (!CheckString.CheckARName(fileName))
                {
                    continue;
                }
                //格式符合:  3月考勤记录1。
                xlsFilePathList.Add(xlsFile);
            }
            #region 先判断第四行,是否全为数字。
            if (!check4thRow(xlsFilePathList, out maxColIndexOfCheckedNameOfExcel))
            {
                return;
            }
            #endregion
            #region 保存关键信息到后台.
            checkNameBGWorker.RunWorkerAsync();
            #endregion
            //开启后台工作者
        }
Esempio n. 11
0
        private void SaveAs(object sender, ExecutedRoutedEventArgs e)
        {
            FileNameDialog dialog = new FileNameDialog("", "Save As", "Please enter the name for the new file:");

FileNamePick:

            if (!((bool)dialog.ShowDialog()))
            {
                return;
            }
            else
            {
                if (dialog.FileName == "" || dialog.FileName == " " || dialog.FileName == "  ")
                {
                    MessageBox.Show("Invalid file name. File name cannot be blank.", "Invalid name picked", MessageBoxButton.OK, MessageBoxImage.Warning);
                    goto FileNamePick;
                }

                try
                {
                    if (!fileManager.SaveFileItemsToFile(new List <FileItem>(fileItems), dialog.FileName, false))
                    {
                        switch (MessageBox.Show("There already exists a file called " + dialog.FileName + ". Do you wish to overwrite it?", "File already exists", MessageBoxButton.YesNoCancel, MessageBoxImage.Question, MessageBoxResult.No))
                        {
                        case MessageBoxResult.Yes: fileManager.SaveFileItemsToFile(new List <FileItem>(fileItems), dialog.FileName, true); break;

                        case MessageBoxResult.Cancel:
                        case MessageBoxResult.None: return;

                        case MessageBoxResult.No:
                        {
                            dialog = new FileNameDialog(dialog.FileName, "Pick another name", "Please pick another name for the new file:");
                            goto FileNamePick;
                        }
                        }
                    }

                    saved                = true;
                    fileItems            = new ObservableCollection <FileItem>(fileManager.LoadFileItemsFromFile(dialog.FileName));
                    dataGrid.ItemsSource = null;
                    dataGrid.ItemsSource = fileItems;
                    Title                = (new FileInfo(dialog.FileName).Name) + " - RubikTimer Satistic files Editor";
                    ViewSuccessSave();
                }

                catch (Exception ex) { ViewFailSave(ex); }
            }
        }
Esempio n. 12
0
        public static FileNameDialog CreateBlueprintRenameDialog()
        {
            GameObject     blueprintNameDialogParent = GameScreenManager.Instance.GetParent(GameScreenManager.UIRenderTarget.ScreenSpaceOverlay);
            FileNameDialog blueprintNameDialog       = Util.KInstantiateUI <FileNameDialog>(ScreenPrefabs.Instance.FileNameDialog.gameObject, blueprintNameDialogParent);

            blueprintNameDialog.name = "BlueprintNameDialog";

            Transform titleTransform = blueprintNameDialog.transform.Find("Panel")?.Find("Title_BG")?.Find("Title");

            if (titleTransform != null && titleTransform.GetComponent <LocText>() != null)
            {
                titleTransform.GetComponent <LocText>().text = "NAME BLUEPRINT";
            }

            return(blueprintNameDialog);
        }
Esempio n. 13
0
        private void btnImportProductsCost_Click(object sender, EventArgs e)
        {
            string xlsFilePath = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择成衣成本记录:", "*.jpg,*.jpeg|*.jpg;*.jpeg", defaultDir);

            if (string.IsNullOrEmpty(xlsFilePath))
            {
                return;
            }
            if (!File.Exists(xlsFilePath))
            {
                return;
            }
            tbPath.Text = xlsFilePath;
            //关闭窗体。
            this.Close();
        }
        private void exportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (CmdHelper.ifExistsTheProcessByName("EXCEL"))
            {
                return;
            }
            string _fileName = "同名工序_" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";

            xlsFilePath = FileNameDialog.getSaveFileNameWithDefaultDir("同名工序汇总:", "*.xls|*.xls", defaultDir, _fileName);
            if (!xlsFilePath.Contains(@"\"))
            {
                return;
            }
            System.Data.DataTable dt = (System.Data.DataTable)dgv.DataSource;
            ExcelHelper.saveDtToExcelWithProgressBar(dt, xlsFilePath, pb);
            //((FrmMainOfProductsCost)this.ParentForm).notifyIcon.ShowBalloonTip(7000, "提示:","汇总保存于: " + xlsFilePath, ToolTipIcon.Info);
            ShowResult.show(lblResult, "汇总保存于: " + xlsFilePath, true);
            timerRestoreLblResult.Start();
        }
Esempio n. 15
0
        public void TriggerTextDialog()
        {
            FileNameDialog textDialog = CreateTextDialog("");

            //textDialog.name = StringBoxTitle;
            textDialog.onConfirm = (System.Action <string>)(name =>
            {
                if (name != null)
                {
                    name = name.Substring(0, Math.Max(0, name.Length - 4));

                    GeyserConfigurator.GeyserType type = GeyserConfigurator.FindType((HashedString)name);

                    ChangeGeyserElement(this.gameObject, type?.id);
                }
            });

            SpeedControlScreen.Instance.Pause(false);
            textDialog.Activate();
        }
Esempio n. 16
0
                    static void OnConfirmDelegate(string blueprintFolder, FileNameDialog parent)
                    {
                        string newFolder = blueprintFolder.Trim(' ', '/', '\\', Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

                        if (newFolder == BlueprintsState.SelectedBlueprint.Folder)
                        {
                            PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, BlueprintsStrings.STRING_BLUEPRINTS_USE_FOLDERBLUEPRINT_NA, null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.Options.FXTime);
                        }

                        else
                        {
                            string blueprintName = BlueprintsState.SelectedBlueprint.FriendlyName;

                            BlueprintsState.SelectedBlueprint.SetFolder(newFolder);
                            PopFXManager.Instance.SpawnFX(BlueprintsAssets.BLUEPRINTS_CREATE_ICON_SPRITE, string.Format(BlueprintsStrings.STRING_BLUEPRINTS_USE_MOVEDBLUEPRINT, blueprintName, newFolder), null, PlayerController.GetCursorPos(KInputManager.GetMousePos()), BlueprintsAssets.Options.FXTime);
                        }

                        SpeedControlScreen.Instance.Unpause(false);
                        parent.Deactivate();
                    }
Esempio n. 17
0
        private string PromptForFileName(string folder, string defaultExt)
        {
            DirectoryInfo dir = new DirectoryInfo(folder);

            IVsUIShell uiShell = (IVsUIShell)_packageService.GetService(typeof(SVsUIShell));

            var dialog = new FileNameDialog(uiShell, dir.Name, defaultExt);

            //get the owner of this dialog
            uiShell.GetDialogOwnerHwnd(out IntPtr hwnd);
            dialog.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            uiShell.EnableModeless(0);
            try
            {
                WindowHelper.ShowModal(dialog, hwnd);
                return((dialog.DialogResult.HasValue && dialog.DialogResult.Value) ? dialog.Input : string.Empty);
            }
            finally
            {
                // This will take place after the window is closed.
                uiShell.EnableModeless(1);
            }
        }
Esempio n. 18
0
            public static void Postfix(FileNameDialog __instance, TMP_InputField ___inputField)
            {
                if (__instance.name.StartsWith("BlueprintsMod_"))
                {
                    ___inputField.onValueChanged.RemoveAllListeners();
                    ___inputField.onEndEdit.RemoveAllListeners();

                    if (__instance.name.StartsWith("BlueprintsMod_FolderDialog_"))
                    {
                        ___inputField.onValueChanged.AddListener(delegate(string text) {
                            for (int i = text.Length - 1; i >= 0; --i)
                            {
                                if (i < text.Length && BlueprintsAssets.BLUEPRINTS_PATH_DISALLOWEDCHARACTERS.Contains(text[i]))
                                {
                                    text = text.Remove(i, 1);
                                }
                            }

                            ___inputField.text = text;
                        });
                    }
                }
            }
Esempio n. 19
0
        public static FileNameDialog CreateTextDialog(string title, bool allowEmpty = false, System.Action <string, FileNameDialog> onConfirm = null)
        {
            GameObject     textDialogParent = GameScreenManager.Instance.GetParent(GameScreenManager.UIRenderTarget.ScreenSpaceOverlay);
            FileNameDialog textDialog       = Util.KInstantiateUI <FileNameDialog>(ScreenPrefabs.Instance.FileNameDialog.gameObject, textDialogParent);

            textDialog.name = "BlueprintsMod_TextDialog_" + title;

            TMP_InputField inputField    = Traverse.Create(textDialog).Field("inputField").GetValue <TMP_InputField>();
            KButton        confirmButton = Traverse.Create(textDialog).Field("confirmButton").GetValue <KButton>();

            if (inputField != null && confirmButton && confirmButton != null && allowEmpty)
            {
                confirmButton.onClick += delegate
                {
                    if (textDialog.onConfirm != null && inputField.text != null && inputField.text.Length == 0)
                    {
                        textDialog.onConfirm.Invoke(inputField.text);
                    }
                };
            }

            if (onConfirm != null)
            {
                textDialog.onConfirm += delegate(string result) {
                    onConfirm.Invoke(result.Substring(0, Mathf.Max(0, result.Length - 4)), textDialog);
                };
            }

            Transform titleTransform = textDialog.transform.Find("Panel")?.Find("Title_BG")?.Find("Title");

            if (titleTransform != null && titleTransform.GetComponent <LocText>() != null)
            {
                titleTransform.GetComponent <LocText>().text = title;
            }

            return(textDialog);
        }
Esempio n. 20
0
        /// <summary>
        /// Calls camera API to capture photo or video
        /// </summary>
        public static async Task <StorageFile> RecordMediaAsync()
        {
            CameraCaptureUI captureUI = new CameraCaptureUI();

            captureUI.PhotoSettings.Format        = CameraCaptureUIPhotoFormat.Jpeg;
            captureUI.PhotoSettings.AllowCropping = false;

            StorageFile storageFile = await captureUI.CaptureFileAsync(CameraCaptureUIMode.PhotoOrVideo);

            if (storageFile == null)
            {
                // User cancelled capture
                return(null);
            }

            // prompt user to enter file name for the new attachment
            FileNameDialog fnd = new FileNameDialog();
            await fnd.ShowAsync();

            // rename file
            await storageFile.RenameAsync(fnd.FileName + storageFile.FileType, NameCollisionOption.ReplaceExisting);

            return(storageFile);
        }
Esempio n. 21
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void ExecuteAsync(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            var item = _dte.SelectedItems.Item(1);
            Helpers.DteHelpers.GetSelectionData(_dte, out var targetFile, out var projectFolderPath, out var projectFullName);
            var targetFolder = Path.GetDirectoryName(targetFile);

            if (string.IsNullOrEmpty(targetFolder) || !Directory.Exists(targetFolder))
                return;

            var selectedItem = item as ProjectItem;
            var selectedProject = item as Project;
            var project = selectedItem?.ContainingProject ?? selectedProject ?? DteHelpers.GetActiveProject(_dte);

            var root = Directory.GetParent(AureliaHelper.RootFolder).FullName.Replace(@"\", @"\\"); //escape for pregex
            var relativePath = Regex.Replace(targetFolder, root, "", RegexOptions.IgnoreCase).Substring(1); // remove starting slash
            var fileNameDialog = new FileNameDialog(relativePath)
            {
                Title = "Generate Attribute",
                IsGlobal = true,
                PreviewText = "Please enter the name of the attribute you would like to create. eg. RedBox"
            };

            fileNameDialog.GlobalChecked(targetFolder.ToLower() == AureliaHelper.GetResouceDirectory.ToLower() || targetFolder.ToLower() == AureliaHelper.GetAttributesDirectory.ToLower() || targetFile.ToLower().Equals(AureliaHelper.ResourceGlobalFile.ToLower()));

            var dialog = _dte.OpenDialog(fileNameDialog);
            if (!(dialog.ShowDialog() ?? false)) { return; }
            var elementName = dialog.Input;
            var templates = Template.GetTemplateFilesByType("attribute").ToList();
            targetFolder = dialog.IsGlobal ? AureliaHelper.GetAttributesDirectory : targetFolder;

            var filesToOpen = await Task.WhenAll(templates.Select(templateName => Template.GenerateTemplatesAsync(templateName, targetFolder, dialog.Input, dialog.IsGlobal)));
            filesToOpen.ToList().ForEach(fullFileName => VsShellUtilities.OpenDocument(package, fullFileName));


        }
Esempio n. 22
0
        private void btnImportEmpsInfo_Click(object sender, EventArgs e)
        {
            FTPHelper ftpHelper = new FTPHelper();

            xlsFilePath = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择考勤记录:", "*.xls|*.xls", defaultDir);
            tb.Text     = xlsFilePath;
            string dir = DirectoryHelper.getDirOfFile(xlsFilePath);

            if (string.IsNullOrEmpty(dir))
            {
                return;
            }
            List <string> xlsFilePathList = DirectoryHelper.getXlsFileUnderThePrescribedDir(dir);

            for (int i = 0; i <= xlsFilePathList.Count - 1; i++)
            {
                //上传文件.
                ftpHelper.UpLoadFile(xlsFilePathList[i], ftpHelper.FtpURI + DirectoryHelper.getFileName(xlsFilePathList[i]));
            }
            //隐藏
            this.MdiParent.WindowState   = FormWindowState.Minimized;
            this.MdiParent.ShowInTaskbar = false;
            //启动定时器
        }
        private void toAWholePiece()
        {
            killHwndOfXls();
            Queue <int> prefix_Of_Staffs_Queue = V_AR_RESULT.get_Prefix_Staffs(YearAndMonthStr);

            if (prefix_Of_Staffs_Queue.Count == 0)
            {
                ShowResult.show(lblResult, "尚未导入本月的考勤记录!", false);
                timerRestoreTheLblResult.Enabled = true;
                return;
            }
            MSG msg = new MSG();
            ApplicationClass app = new ApplicationClass();
            //追加Hwnd到队列中.
            int appHwnd = app.Hwnd;

            app.Visible = false;
            Workbook  wBook       = app.Workbooks.Add(true);
            Worksheet wSheet      = (Worksheet)wBook.Worksheets[1];
            string    _defaultDir = System.Windows.Forms.Application.StartupPath + "\\考勤汇总";
            int       seq         = prefix_Of_Staffs_Queue.Dequeue();
            int       lastSeq     = 0;

            while (prefix_Of_Staffs_Queue.Count >= 1)
            {
                lastSeq = prefix_Of_Staffs_Queue.Dequeue();
            }
            string _fileName = YearAndMonthStr + "_考勤汇总" + seq.ToString() + "-" + lastSeq.ToString() + ".xls";

            if (!xlsFilePath.Contains(":"))
            {
                //导出到Excel中
                xlsFilePath = FileNameDialog.getSaveFileNameWithDefaultDir("考勤汇总:", "*.xls|*.xls", _defaultDir, _fileName);
                if (!xlsFilePath.Contains(@"\"))
                {
                    return;
                }
            }
            //依据前缀和月份获取列表。
            //获取该月该考勤机的出勤人数。
            int AR_Num = V_AttendanceRecord.getARNumByYearAndMonth(YearAndMonthStr);

            if (AR_Num == 0)
            {
                MessageBox.Show("数据源为空,无法导出。", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            int rowMaxCount = AR_Num * 2 + 6;
            int colMaxCount = AttendanceR.get_AR_Days_Num(YearAndMonthStr);

            //写标题
            try
            {
                //每行格式设置,注意标题占一行。
                Range range = wSheet.get_Range(wSheet.Cells[1, 1], wSheet.Cells[rowMaxCount + 1, colMaxCount + 1]);
                //设置单元格为文本。
                range.NumberFormatLocal = "@";
                //水平对齐方式
                range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                //第一行写考勤分析结果。
                wSheet.Cells[1, 1] = YearAndMonthStr + " 考勤分析结果" + seq.ToString() + "-" + lastSeq.ToString();
                //获取该日期详细的考勤记录。
                #region
                V_AttendanceRecord.AR_Properties aR_Properties = V_AttendanceRecord.getARProperties(YearAndMonthStr);
                //第三行:考勤时间
                wSheet.Cells[3, 1] = "考勤时间";
                wSheet.Cells[3, 3] = String.Format(@"{0} ~ {1}",
                                                   aR_Properties.Start_Date,
                                                   aR_Properties.End_Date);
                wSheet.Cells[3, 10] = "制表时间";
                wSheet.Cells[3, 12] = aR_Properties.Tabulation_date;
                #endregion
                List <int> dayList = V_AR_DETAIL.getDayListOfTheSpecificMonth(YearAndMonthStr);
                //需要统计有多少人。
                int total_num_of_AttendanceR = AttendanceR.get_Total_Num_Of_Staffs_By_YAndM(YearAndMonthStr);
                pb.Value          = 0;
                pb.Maximum        = dayList.Count + dayList.Count * total_num_of_AttendanceR;
                pb.Visible        = true;
                lblPrompt.Text    = _fileName + ":";
                lblPrompt.Visible = true;
                //写 此月与考勤相关的日。
                for (int i = 0; i <= dayList.Count - 1; i++)
                {
                    //写该月的具体有哪些日:1,2,3.与考勤相关。
                    wSheet.Cells[4, i + 1] = dayList[i].ToString();
                    pb.Value++;
                }
                //实际出勤天数.
                wSheet.Cells[4, dayList.Count + 1] = "实际出勤天数";
                //事假
                wSheet.Cells[4, dayList.Count + 2] = "事假";
                //未打卡
                wSheet.Cells[4, dayList.Count + 3] = "未打卡";
                //延点
                wSheet.Cells[4, dayList.Count + 4] = "延点(小时)";
                //迟到
                wSheet.Cells[4, dayList.Count + 5] = "迟到";
                //早退
                wSheet.Cells[4, dayList.Count + 6] = "早退";
                //餐补
                wSheet.Cells[4, dayList.Count + 7] = "餐补";
                string             AR_YEAR_AND_Month_Str = String.Empty;
                string             AR_Day = string.Empty;
                List <V_AR_DETAIL> v_AR_Detail_Specific_Day_List = null;
                for (int j = 1; j <= dayList.Count; j++)
                {
                    AR_YEAR_AND_Month_Str = aR_Properties.Start_Date.Substring(0, 8);
                    AR_Day = AR_YEAR_AND_Month_Str + dayList[j - 1].ToString().PadLeft(2, '0');
                    v_AR_Detail_Specific_Day_List = V_AR_DETAIL.get_V_AR_Detail_By_Specific_Day(AR_Day);
                    //按日取。
                    for (int i = 0; i <= v_AR_Detail_Specific_Day_List.Count - 1; i++)
                    {
                        V_AR_DETAIL v_AR_Detail = v_AR_Detail_Specific_Day_List[i];
                        if (j == 1)
                        {
                            //第五行写工号。
                            wSheet.Cells[5 + i * 2, 1] = "工号";
                            //获取原始的工号,没有前缀。
                            wSheet.Cells[5 + i * 2, 3] = "'" + v_AR_Detail.Job_number;
                            //9
                            wSheet.Cells[5 + i * 2, 9] = "姓名";
                            //11
                            wSheet.Cells[5 + i * 2, 11] = v_AR_Detail.Name;
                            //19
                            wSheet.Cells[5 + i * 2, 19] = "部门";
                            //21
                            wSheet.Cells[5 + i * 2, 21] = v_AR_Detail.Dept;
                            V_Summary_OF_AR       v_summary_of_ar = new V_Summary_OF_AR(v_AR_Detail.Job_number, YearAndMonthStr);
                            System.Data.DataTable dtARSummary     = v_summary_of_ar.getSummaryOFAR();
                            //实际出勤天数.
                            wSheet.Cells[6 + i * 2, dayList.Count + 1] = dtARSummary.Rows[0]["AR_DAYS"].ToString();
                            //事假
                            string vacatioin_total_time = dtARSummary.Rows[0]["VACATION_TOTAL_TIME"].ToString();
                            wSheet.Cells[6 + i * 2, dayList.Count + 2] = "0".Equals(vacatioin_total_time) ? "" : vacatioin_total_time;
                            string not_Finger_Print_num = dtARSummary.Rows[0]["NOT_FINGERPRINT_TIMES"].ToString();
                            //未打卡
                            wSheet.Cells[6 + i * 2, dayList.Count + 3] = "0".Equals(not_Finger_Print_num) ? "" : not_Finger_Print_num;
                            string delayTime = dtARSummary.Rows[0]["DELAY_TOTAL_TIME"].ToString();
                            //延点
                            wSheet.Cells[6 + i * 2, dayList.Count + 4] = "0.0".Equals(delayTime) ? "" : delayTime;
                            string come_late_Num = dtARSummary.Rows[0]["COME_LATE_NUM"].ToString();
                            //迟到
                            wSheet.Cells[6 + i * 2, dayList.Count + 5] = "0".Equals(come_late_Num) ? "" : come_late_Num;
                            string leave_early_num = dtARSummary.Rows[0]["LEAVE_EARLY_NUM"].ToString();
                            //早退
                            wSheet.Cells[6 + i * 2, dayList.Count + 6] = "0".Equals(leave_early_num) ? "" : leave_early_num;
                            //餐补
                            wSheet.Cells[6 + i * 2, dayList.Count + 7] = dtARSummary.Rows[0]["DINNER_SUBSIDY_NUM"].ToString();
                        }
                        System.Data.DataTable dt = V_AR_Time_Helper.getARTime(v_AR_Detail.Job_number, AR_Day);
                        string tempStr           = String.Empty;
                        int    length            = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1.ToString().Length;
                        for (int k = 0; k <= dt.Rows.Count - 1; k++)
                        {
                            //先设置颜色.
                            if ("0".Equals(dt.Rows[k]["FLAG"].ToString()))
                            {
                                if ("1".Equals(dt.Rows[k]["COME_LATE_NUM"].ToString())) //迟到
                                {
                                    //先计算单元格已有字符长度。
                                    length = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1.ToString().Length;
                                    //迟到
                                    tempStr = dt.Rows[k]["TIME"].ToString() + (k < dt.Rows.Count - 1 ? "\r\n" : "");
                                    ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 + tempStr;
                                    ((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.Color = -16776961;
                                    continue;
                                }
                                if ("1".Equals(dt.Rows[k]["LEAVE_EARLY_NUM"].ToString()))
                                {
                                    //先计算单元格已有字符长度。
                                    length = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1.ToString().Length;
                                    //早退
                                    tempStr = dt.Rows[k]["TIME"].ToString() + (k < dt.Rows.Count - 1 ? "\r\n" : "");
                                    ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 + tempStr;
                                    //写完即改变前景色。
                                    ((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.Color = -16776961;
                                    continue;
                                }
                                //先计算单元格已有字符长度。
                                length = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1.ToString().Length;
                                //正常
                                //正常上班点.
                                tempStr = dt.Rows[k]["TIME"].ToString() + (k < dt.Rows.Count - 1 ? "\r\n" : "");
                                ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 + tempStr;
                                ((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.Color = System.Drawing.Color.FromArgb(0, 0, 0).ToArgb();
                                continue;
                            }
                            //先计算单元格已有字符长度。
                            length = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1.ToString().Length;
                            //请假点。
                            tempStr = "<" + dt.Rows[k]["TIME"].ToString() + ">" + (k < (dt.Rows.Count - 1) ? "\r\n" : "");
                            ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 = ((Range)wSheet.Cells[6 + i * 2, j]).FormulaR1C1 + tempStr;
                            //((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.Bold = true;
                            //((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.ThemeColor = XlThemeColor.xlThemeColorDark1;
                            //((Range)wSheet.Cells[6 + i * 2, j]).Characters[length + 1, 5].Font.Color = -16776961;
                        }
                        pb.Value++;
                    }
                }
                rowMaxCount = wSheet.UsedRange.Rows.Count;
                //休息日,背景色变为浅绿色。
                for (int j = 1; j <= dayList.Count; j++)
                {
                    bool ifRestDay = false;
                    AR_YEAR_AND_Month_Str = aR_Properties.Start_Date.Substring(0, 8);
                    AR_Day    = AR_YEAR_AND_Month_Str + dayList[j - 1].ToString().PadLeft(2, '0');
                    ifRestDay = Have_A_Rest_Helper.ifDayOfRest(AR_Day);
                    if (ifRestDay)
                    {
                        //此列背景色改为:

                        /*
                         *  ange("AF102").Select
                         *  With Selection.Interior
                         *      .Pattern = xlSolid
                         *      .PatternColorIndex = xlAutomatic
                         *       .ThemeColor = xlThemeColorAccent3
                         *       .TintAndShade = 0.599993896298105
                         *      .PatternTintAndShade = 0
                         *  End With
                         * End Sub
                         */
                        Range rangeRestDay = wSheet.get_Range(wSheet.Cells[4, j], wSheet.Cells[rowMaxCount, j]);
                        rangeRestDay.Interior.Pattern             = XlPattern.xlPatternSolid;
                        rangeRestDay.Interior.PatternColorIndex   = XlPattern.xlPatternAutomatic;
                        rangeRestDay.Interior.ThemeColor          = XlThemeColor.xlThemeColorAccent3;
                        rangeRestDay.Interior.TintAndShade        = 0.599993896298105;
                        rangeRestDay.Interior.PatternTintAndShade = 0;
                    }
                }
                //合并第一行
                Range rangeTitle = wSheet.get_Range(wSheet.Cells[1, 1], wSheet.Cells[1, dayList.Count + 7]);
                rangeTitle.Merge();
                rangeTitle.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                rangeTitle.VerticalAlignment   = XlVAlign.xlVAlignCenter;
                pb.Visible        = false;
                lblPrompt.Visible = false;
                //自动调整列宽
                //range.EntireColumn.AutoFit();
                //设置禁止弹出保存和覆盖的询问提示框
                app.DisplayAlerts          = false;
                app.AlertBeforeOverwriting = false;
                //保存excel文档并关闭
                wBook.SaveAs(xlsFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                wBook.Close(true, xlsFilePath, Type.Missing);
                //退出Excel程序
                app.Quit();
                //释放资源
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wSheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                //调用GC的垃圾收集方法
                GC.Collect();
                GC.WaitForPendingFinalizers();
                ShowResult.show(lblResult, "存于: " + xlsFilePath, true);
                timerRestoreTheLblResult.Enabled = true;
                //生成工作安排表。
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示消息:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportEmpsARInfo_Click(object sender, EventArgs e)
        {
            //判断是否存在Excel进程.
            if (CmdHelper.ifExistsTheProcessByName("EXCEL.EXE"))
            {
                ShowResult.show(lblResult, "存在未关闭的Office Excel进程,请先关闭!", false);
                return;
            }
            string _uncertainWSPath = _defaultDir + "\\uncertainRecord_" + TimeHelper.getCurrentTimeStr() + ".xls";

            this.dgv.Visible = false;
            this.dgv_same_pinyin_of_name.Visible = true;
            this.dgv_same_name.Visible           = false;
            dgv_same_name.DataSource             = null;
            dgv_same_pinyin_of_name.DataSource   = null;
            dgv.DataSource      = null;
            lblResult.Text      = "";
            lblResult.BackColor = this.BackColor;
            tb.Clear();
            randomStr   = TimeHelper.getCurrentTimeStr();
            xlsFilePath = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择考勤记录:", "*.xls|*.xls", defaultDir);
            string dir = DirectoryHelper.getDirOfFile(xlsFilePath);

            if (string.IsNullOrEmpty(dir))
            {
                return;
            }
            List <string> xlsFileList = DirectoryHelper.getXlsFileUnderThePrescribedDir(dir);
            List <string> resultList  = new List <string>();

            foreach (string xlsFile in xlsFileList)
            {
                string fileName = DirectoryHelper.getFileNameWithoutSuffix(xlsFile);
                if (!CheckString.CheckARName(fileName))
                {
                    continue;
                }
                //格式符合:  3月考勤记录1。
                resultList.Add(xlsFile);
            }
            #region 先判断第四行,是否全为数字。
            int maxColIndex = 0;
            if (!check4thRow(resultList, out maxColIndex))
            {
                return;
            }
            #endregion
            if (cbCheckSameNamesButDifferentMachineNo.Checked)
            {
                #region 保存关键信息到后台.
                saveCriticalARInfo(resultList);
                #endregion
                #region  打开4个考勤文件
                for (int i = 1; i <= resultList.Count; i++)
                {
                    switch (i)
                    {
                    case 1:
                        _1th_my_excel = new MyExcel(resultList[0]);
                        _1th_my_excel.open();
                        _1th_Sheet = _1th_my_excel.getFirstWorkSheetAfterOpen();
                        break;

                    case 2:
                        _2nd_my_excel = new MyExcel(resultList[1]);
                        _2nd_my_excel.open();
                        _2nd_Sheet = _2nd_my_excel.getFirstWorkSheetAfterOpen();
                        break;

                    case 3:
                        _3rd_my_excel = new MyExcel(resultList[2]);
                        _3rd_my_excel.open();
                        _3rd_Sheet = _3rd_my_excel.getFirstWorkSheetAfterOpen();
                        break;

                    case 4:
                        _4th_my_excel = new MyExcel(resultList[3]);
                        _4th_my_excel.open();
                        _4th_Sheet = _4th_my_excel.getFirstWorkSheetAfterOpen();
                        break;
                    }
                }
                #endregion
                #region 创建 _uncertain_myExcel;
                MyExcel uncertainRecordExcel = null;
                uncertainRecordExcel = new MyExcel(_uncertainWSPath);
                uncertainRecordExcel.create();
                uncertainRecordExcel.open();
                uncertainWS = uncertainRecordExcel.getFirstWorkSheetAfterOpen();
                //先写,日期行。
                Usual_Excel_Helper uEHelper = new Usual_Excel_Helper(uncertainWS);
                uEHelper.writeToSpecificRow(1, 1, maxColIndex);
                #endregion
                System.Data.DataTable dt   = getSamePinYinButName();
                bool have_same_pinyin_flag = false;
                if (dt != null && dt.Rows.Count > 0)
                {
                    have_same_pinyin_flag = true;
                }
                //*************判断是否拼音相同 开始********************8
                if (have_same_pinyin_flag)
                {
                    this.dgv_same_pinyin_of_name.Visible    = true;
                    this.dgv_same_pinyin_of_name.DataSource = dt;
                    DGVHelper.AutoSizeForDGV(dgv_same_pinyin_of_name);
                    ShowResult.show(lblResult, "存在姓名拼音相同的记录!", false);
                    this.lblPrompt.Visible           = false;
                    timerRestoreTheLblResult.Enabled = true;
                    btnSwitch.Text = "查看拼音相同的记录";
                    btnSwitch_Click(sender, e);
                    #region 写记录到不确定文档中.
                    int theRowIndex           = 0;
                    int Attendance_Machine_No = 0;
                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        theRowIndex           = int.Parse(dt.Rows[i]["行号"].ToString());
                        Attendance_Machine_No = int.Parse(dt.Rows[i]["卡机编号"].ToString());
                        switch (Attendance_Machine_No)
                        {
                        case 1:
                            //获取源区域
                            srcRange = _1th_Sheet.Range[_1th_Sheet.Cells[theRowIndex, 1], _1th_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;

                            destRange = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            //保存一下。
                            break;

                        case 2:
                            srcRange = _2nd_Sheet.Range[_2nd_Sheet.Cells[theRowIndex, 1], _2nd_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;

                            destRange = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;

                        case 3:
                            srcRange = _3rd_Sheet.Range[_3rd_Sheet.Cells[theRowIndex, 1], _3rd_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;

                        case 4:
                            srcRange = _4th_Sheet.Range[_4th_Sheet.Cells[theRowIndex, 1], _4th_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;
                        }
                    }
                    //显示该文档
                    CmdHelper.runCmd(_uncertainWSPath);
                    #endregion
                    string promptStr = string.Format(@"存在姓名拼音相同的记录。{0}
                                                                              继续(OK), 取消导入(Cancel)。", "\r\n");
                    if (DialogResult.Cancel.Equals(MessageBox.Show(promptStr, "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)))
                    {
                        uncertainWS.UsedRange.ColumnWidth = 3.75M;
                        uncertainRecordExcel.saveWithoutAutoFit();
                        uncertainRecordExcel.close();
                        closeThe4ARExcels();
                        return;
                    }
                }
                //closeThe4ARExcels();
                //*************判断是否拼音相同  结束*****************88
                //1.h
                dt = getSameNameInfo();
                string prompt = string.Empty;
                if (dt.Rows.Count != 0)
                {
                    btnSwitch.Text = "查看同名记录";
                    btnSwitch_Click(sender, e);

                    int theRowIndex           = 0;
                    int Attendance_Machine_No = 0;
                    #region   记录书写结束.
                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        theRowIndex           = int.Parse(dt.Rows[i]["行号"].ToString());
                        Attendance_Machine_No = int.Parse(dt.Rows[i]["卡机编号"].ToString());
                        switch (Attendance_Machine_No)
                        {
                        case 1:
                            //获取源区域
                            srcRange = _1th_Sheet.Range[_1th_Sheet.Cells[theRowIndex, 1], _1th_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            //保存一下。
                            break;

                        case 2:
                            srcRange = _2nd_Sheet.Range[_2nd_Sheet.Cells[theRowIndex, 1], _2nd_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;

                        case 3:
                            srcRange = _3rd_Sheet.Range[_3rd_Sheet.Cells[theRowIndex, 1], _3rd_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;

                        case 4:
                            srcRange = _4th_Sheet.Range[_4th_Sheet.Cells[theRowIndex, 1], _4th_Sheet.Cells[theRowIndex + 1, maxColIndex]];
                            srcRange.Cells.Copy(Type.Missing);
                            //向目标复制。
                            //或取目标单元格。
                            currentRow = uncertainWS.UsedRange.Rows.Count;
                            destRange  = uncertainWS.Range[uncertainWS.Cells[currentRow + 1, 1], uncertainWS.Cells[currentRow + 2, maxColIndex]];
                            //destRange.Select();
                            uncertainWS.Paste(destRange, false);
                            break;
                        }
                    }
                    #endregion
                    prompt = string.Format(@"存在同名记录,将合并;{0}
                                                                              继续(OK), 取消导入(Cancel)。", "\r\n");
                    if (DialogResult.Cancel.Equals(MessageBox.Show(prompt, "提示:", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)))
                    {
                        uEHelper.setAllColumnsWidth(3.75M);
                        uncertainRecordExcel.saveWithoutAutoFit();
                        uncertainRecordExcel.close();
                        closeThe4ARExcels();
                        return;
                    }
                }
                //关闭不确定文档。
                uEHelper.setAllColumnsWidth(3.75M);
                uncertainRecordExcel.saveWithoutAutoFit();
                uncertainRecordExcel.close();
                closeThe4ARExcels();
            }
            resultList.Sort();
            //判断该考勤机中是否已经存在,某月的记录
            foreach (string xlsFilePath in resultList)
            {
                string fileName = DirectoryHelper.getFileNameWithoutSuffix(xlsFilePath);
                int    attendanceMachineFlag = int.Parse(fileName.Substring(fileName.Length - 1, 1));
                //打开文档获取考勤机,所记录的日期。
                MyExcel myExcel = new MyExcel(xlsFilePath);
                myExcel.open();
                Worksheet          firstSheet         = myExcel.getFirstWorkSheetAfterOpen();
                Usual_Excel_Helper uEHelper           = new Usual_Excel_Helper(firstSheet);
                string             year_and_month_str = uEHelper.getCellContentByRowAndColIndex(3, 3);
                year_and_month_str = year_and_month_str.Substring(0, 7);
                myExcel.close();
                System.Data.DataTable dtSubmitInfo = getSubmitInfoOfTheSpecificeMachineAndYearAndMonth(attendanceMachineFlag, year_and_month_str);
                if (!"0".Equals(dtSubmitInfo.Rows[0]["nums_of_staffs"].ToString()))
                {
                    string prompt = string.Format(@"您已经于: {1},{0}提交了{2} 考勤机{3},{0}共计{4}个用户的纪录{0}    覆盖(OK),退出(Cancel)?", "\r\n", dtSubmitInfo.Rows[0]["latest_record_time"].ToString(), year_and_month_str, attendanceMachineFlag, dtSubmitInfo.Rows[0]["nums_of_staffs"].ToString());
                    if (DialogResult.Cancel.Equals(MessageBox.Show(prompt, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)))
                    {
                        return;
                    }
                    delTheInfoOfTheSpecificeMachineAndYearAndMonth(attendanceMachineFlag, year_and_month_str);
                }
            }
            this.dgv.DataSource = null;
            //this.dgv.Columns.Clear();
            lblPrompt.Visible = false;
            lblPrompt.Text    = "";
            pb.Value          = 0;
            pb.Maximum        = 0;
            pb.Visible        = false;
            foreach (string xlsFilePath in resultList)
            {
                tb.Text           = xlsFilePath;
                lblResult.Visible = false;
                MSG msg = AttendanceRHelper.ImportAttendanceRecordToDB(xlsFilePath, randomStr, lblPrompt, pb, lblResult);
                //导入完成后进行保存,保存该文件至prepared目录中
                pb.Visible        = false;
                lblPrompt.Visible = false;
                ShowResult.show(lblResult, msg.Msg, msg.Flag);
                timerRestoreTheLblResult.Enabled = true;
                if (!msg.Flag)
                {
                    return;
                }
                //saveTheExcel(xlsFilePath);
            }
            dgv_same_name.Visible           = false;
            dgv_same_pinyin_of_name.Visible = false;
            //加载导入的数据。
            this.dgv.DataSource = null;
            this.dgv.DataSource = aR.getAR(randomStr);
            this.dgv.Visible    = true;
            DGVHelper.AutoSizeForDGV(dgv);
            tb.Clear();
        }
Esempio n. 25
0
        public void Update()
        {
            if ((ParentTool?.hasFocus ?? false) && BlueprintsState.LoadedBlueprints.Count > 0)
            {
                bool blueprintChanged = false;

                if (Input.GetKeyDown(BlueprintsAssets.BLUEPRINTS_KEYBIND_USE_RENAME))
                {
                    FileNameDialog blueprintNameDialog = Utilities.CreateBlueprintRenameDialog();
                    SpeedControlScreen.Instance.Pause(false);

                    blueprintNameDialog.onConfirm = delegate(string blueprintName) {
                        BlueprintsState.SelectedBlueprint.Rename(blueprintName.Substring(0, blueprintName.Length - 4));
                        BlueprintsState.SelectedBlueprint.Write();

                        blueprintNameDialog.Deactivate();
                        SpeedControlScreen.Instance.Unpause(false);
                    };

                    blueprintNameDialog.Activate();
                }

                else if (Input.GetKeyDown(BlueprintsAssets.BLUEPRINTS_KEYBIND_USE_DELETE))
                {
                    BlueprintsState.SelectedBlueprint.DeleteFile();
                    BlueprintsState.LoadedBlueprints.RemoveAt(BlueprintsState.SelectedBlueprintIndex);
                    if (BlueprintsState.SelectedBlueprintIndex >= BlueprintsState.LoadedBlueprints.Count)
                    {
                        BlueprintsState.SelectedBlueprintIndex = BlueprintsState.LoadedBlueprints.Count - 1;
                    }

                    blueprintChanged = true;
                }

                if (BlueprintsState.LoadedBlueprints.Count > 1)
                {
                    if (Input.GetKeyDown(BlueprintsAssets.BLUEPRINTS_KEYBIND_USE_CYCLELEFT))
                    {
                        if (--BlueprintsState.SelectedBlueprintIndex < 0)
                        {
                            BlueprintsState.SelectedBlueprintIndex = BlueprintsState.LoadedBlueprints.Count - 1;
                        }

                        blueprintChanged = true;
                    }

                    else if (Input.GetKeyDown(BlueprintsAssets.BLUEPRINTS_KEYBIND_USE_CYCLERIGHT))
                    {
                        if (++BlueprintsState.SelectedBlueprintIndex >= BlueprintsState.LoadedBlueprints.Count)
                        {
                            BlueprintsState.SelectedBlueprintIndex = 0;
                        }

                        blueprintChanged = true;
                    }
                }

                if (blueprintChanged)
                {
                    BlueprintsState.ClearVisuals();

                    if (BlueprintsState.LoadedBlueprints.Count > 0)
                    {
                        BlueprintsState.VisualizeBlueprint(Grid.PosToXY(PlayerController.GetCursorPos(KInputManager.GetMousePos())), BlueprintsState.SelectedBlueprint);
                    }

                    else
                    {
                        UseBlueprintTool.Instance.CreateVisualizer();
                    }
                }
            }
        }
        private void btnImportRestDay_Click(object sender, EventArgs e)
        {
            randomStr          = RandomStr.GetRandomString(33, true, true, true, false, "");
            xlsFilePath        = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择考勤记录:", "*.xls|*.xls", defaultDir);
            tbRestDayPath.Text = xlsFilePath;
            //***********************************************************
            List <TheDaysOfOvertime> restDayList = new List <TheDaysOfOvertime>();

            ApplicationClass app = new ApplicationClass();

            app.Visible = false;
            Workbook wBook = null;
            //用于确定本月最后一天.
            //行最大值.
            int rowsMaxCount = 0;
            int colsMaxCount = 0;

            try
            {
                wBook = app.Workbooks.Open(xlsFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                if (wBook != null)
                {
                    wBook.Close(true, xlsFilePath, Type.Missing);
                }
                //退出excel
                app.Quit();
                //释放资源
                if (wBook != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook);
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                //调用GC的垃圾回收方法
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return;
            }
            Worksheet ws = (Worksheet)(wBook.Worksheets.Item[1]);

            //行;列最大值 赋值.
            rowsMaxCount = ws.UsedRange.Rows.Count;
            colsMaxCount = ws.UsedRange.Columns.Count;
            //判断首行是否为 考勤记录表;以此判断此表是否为考勤记录表.
            //检查日期列的值是否符合规范。
            string temp = string.Empty;

            string[] tempArray = { };
            for (int rowIndex = 2; rowIndex <= rowsMaxCount; rowIndex++)
            {
                temp = ((Range)ws.Cells[rowIndex, 2]).Text.ToString().Trim();
                DateTime dt;
                if (!DateTime.TryParse(temp, out dt))
                {
                    ShowResult.show(lblResult, temp + ": 非时间格式!", false);
                    timerRestoreTheLblResult.Enabled = true;
                    return;
                }
                //先判断是否含有"/"或者"-"
                if (!temp.Contains("/") && !temp.Contains("-"))
                {
                    ShowResult.show(lblResult, "此内容非时间格式: yyyy/MM/dd 或 yyyy-MM-dd!", false);
                    timerRestoreTheLblResult.Enabled = true;
                    return;
                }

                tempArray = temp.Split(new char[] { '/', '-' });
                string year = tempArray[0];
                if (!CheckString.checkYear(year))
                {
                    ShowResult.show(lblResult, "前4位非年份!", false);
                    timerRestoreTheLblResult.Enabled = true;
                    return;
                }
                string month = tempArray[1];
                if (!CheckString.checkMonth(month))
                {
                    ShowResult.show(lblResult, "第6,7位非月份!", false);
                    timerRestoreTheLblResult.Enabled = true;
                    return;
                }
                string day = tempArray[2];
                if (!CheckString.checkDay(day))
                {
                    ShowResult.show(lblResult, "第9,10位非天数!", false);
                    timerRestoreTheLblResult.Enabled = true;
                    return;
                }
            }
            string dateStr = string.Empty;
            string name    = string.Empty;

            //精诚所至,金石为开。
            for (int rowIndex = 2; rowIndex <= rowsMaxCount; rowIndex++)
            {
                dateStr = ((Range)ws.Cells[rowIndex, 2]).Text.ToString().Trim();
                name    = ((Range)ws.Cells[rowIndex, 1]).Text.ToString().Trim();
                TheDaysOfOvertime restDay = new TheDaysOfOvertime(name, dateStr);
                restDay.addRestDay();
            }
            //释放对象
            int hwndOfApp = app.Hwnd;

            Tools.CmdHelper.killProcessByHwnd(hwndOfApp);
            //****************************************************************
            tempArray           = dateStr.Split(new char[] { '/', '-' });
            this.dgv.DataSource = TheDaysOfOvertime.getRestDays(tempArray[0] + "-" + tempArray[1]);
            DGVHelper.AutoSizeForDGV(dgv);
        }
        /// <summary>
        /// 导入工作安排表。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImportWorkSchedule_Click(object sender, EventArgs e)
        {
            string xlsFilePath = FileNameDialog.getSelectedFilePathWithDefaultDir("请选择要导入的工作安排表", "*.xls|*.xls", string.Format(@"{0}\{1}", Environment.CurrentDirectory, "工作安排表"));

            if (!xlsFilePath.Contains(@"\"))
            {
                return;
            }
            MSG msg = new MSG();
            //导入数据的行数.
            int affectedCount    = 0;
            ApplicationClass app = new ApplicationClass();

            app.Visible = false;
            Workbook wBook = null;
            //用于确定本月最后一天.
            string day = String.Empty;
            //行最大值.
            int rowsMaxCount = 0;
            int colsMaxCount = 0;

            try
            {
                wBook = app.Workbooks.Open(xlsFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                if (wBook != null)
                {
                    wBook.Close(true, xlsFilePath, Type.Missing);
                }
                //退出excel
                app.Quit();
                //释放资源
                if (wBook != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook);
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                //调用GC的垃圾回收方法
                GC.Collect();
                GC.WaitForPendingFinalizers();
                msg.Flag = false;
                msg.Msg  = ex.ToString();
                return;
            }
            Worksheet ws = (Worksheet)(wBook.Worksheets.Item[1]);

            if (!((Range)ws.Cells[1, 1]).Text.ToString().Contains("工作安排"))
            {
                msg.Msg  = "此表非工作安排表";
                msg.Flag = false;
                ShowResult.show(lblResult, msg.Msg, msg.Flag);
                return;
            }
            //行;列最大值 赋值.
            rowsMaxCount = ws.UsedRange.Rows.Count;
            colsMaxCount = ws.UsedRange.Columns.Count;
            string         C3Str           = ((Range)ws.Cells[3, 3]).Text.ToString().Trim();
            string         yearAndMonthStr = C3Str.Split('~')[0].Trim().Substring(0, 8);
            List <V_I_W_S> v_I_W_S_List    = new List <V_I_W_S>();

            //从第二列开始统计
            for (int colIndex = 2; colIndex <= colsMaxCount; colIndex++)
            {
                day = ((Range)ws.Cells[4, colIndex]).Text.ToString().Trim();
                if (String.IsNullOrEmpty(day))
                {
                    continue;
                }
                //从第5行开始.
                for (int rowIndex = 5; rowIndex <= rowsMaxCount; rowIndex++)
                {
                    V_I_W_S v_I_W_S = new V_I_W_S();
                    string  dept    = ((Range)ws.Cells[rowIndex, 1]).Text.ToString().Trim();
                    if (String.IsNullOrEmpty(dept))
                    {
                        continue;
                    }
                    v_I_W_S.Dept    = dept;
                    v_I_W_S.Date    = yearAndMonthStr + day.PadLeft(2, '0');
                    v_I_W_S.BgColor = ((Range)(ws.Cells[rowIndex, colIndex])).Interior.Color;
                    v_I_W_S_List.Add(v_I_W_S);
                }
            }
            for (int j = 0; j <= v_I_W_S_List.Count - 1; j++)
            {
                affectedCount += v_I_W_S_List[j].updateWorkSchedule();
            }
            //释放对象
            int hwndOfApp = app.Hwnd;

            Tools.CmdHelper.killProcessByHwnd(hwndOfApp);
            msg.Flag = true;
            msg.Msg  = String.Format(@"导入完成;计{0}条.", affectedCount.ToString());
            ShowResult.show(lblResult, msg.Msg, msg.Flag);
        }
        public Tools.MSG genExcel(out string xlsFilePath)
        {
            killHwndOfXls();
            MSG    msg             = new MSG();
            string excelName       = _YearAndMonthStr + "_工作安排表.xls";
            string defaultDir      = Environment.CurrentDirectory + string.Format(@"\工作安排表", excelName);
            string xlsFileFullPath = FileNameDialog.getSaveFileNameWithDefaultDir("请选择考勤记录:", "*.xls|*.xls", defaultDir, excelName);

            if (!xlsFileFullPath.Contains(@"\"))
            {
                msg.Flag    = false;
                msg.Msg     = "取消了选择!";
                xlsFilePath = xlsFileFullPath;
                return(msg);
            }
            ApplicationClass app = new ApplicationClass();

            hwndOfXls_Queue.Enqueue(app.Hwnd);
            app.Visible = false;
            Workbook wBook        = null;
            int      rowsMaxCount = 0;
            int      colsMaxCount = 0;

            try
            {
                wBook = app.Workbooks.Add(true);
                Worksheet wS = wBook.Worksheets.Item[1] as Worksheet;
                //每行格式设置,注意标题占一行。
                rowsMaxCount = this.getDeptNum() + 4;
                Queue <int> daysQueue = this.getAllDaysOfThisMonth();
                colsMaxCount = daysQueue.Count;
                //每行格式设置,注意标题占一行。
                Range range = wS.get_Range(wS.Cells[1, 1], wS.Cells[rowsMaxCount + 1, colsMaxCount + 1]);
                //设置单元格为文本。
                range.NumberFormatLocal = "@";
                //水平对齐方式
                range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                //第一行写考勤分析结果。
                wS.Cells[1, 1] = _YearAndMonthStr + " 工作安排分析结果";
                wS.Cells[1, 3] = "休假";
                ((Range)(wS.Cells[1, 4])).Interior.Color = System.Drawing.Color.Green.ToArgb();                //获取该日期详细的考勤记录。
                wS.Cells[1, 5] = "周日";
                ((Range)wS.Cells[1, 6]).Interior.Color = System.Drawing.Color.Yellow.ToArgb();
                V_AR_DETAIL v_AR_Detail = V_AR_DETAIL.get_V_AR_Detail(_YearAndMonthStr);

                //第三行:考勤时间
                wS.Cells[3, 1] = "考勤时间";
                wS.Cells[3, 3] = String.Format(@"{0} ~ {1}",
                                               v_AR_Detail.Start_date,
                                               v_AR_Detail.End_date);
                wS.Cells[3, 10] = "制表时间";
                wS.Cells[3, 12] = v_AR_Detail.Tabulation_time;

                //书写部门
                List <string> deptList = this.getDeptList();
                for (int i = 0; i <= deptList.Count - 1; i++)
                {
                    wS.Cells[5 + i, 1] = deptList[i].ToString();
                }
                string v_w_s_Day = string.Empty;
                //开始书写此月的日子
                int colIndex = 1;
                while (daysQueue.Count > 0)
                {
                    colIndex++;
                    int day = daysQueue.Dequeue();
                    wS.Cells[4, colIndex] = day;
                    v_w_s_Day             = _YearAndMonthStr + "-" + day.ToString().PadLeft(2, '0');
                    for (int i = 0; i <= deptList.Count - 1; i++)
                    {
                        //填写该日内所有部门的休假情况.
                        V_W_S v_W_S = new V_W_S();
                        v_W_S.Dept = deptList[i].ToString();
                        v_W_S.Work_and_rest_date = v_w_s_Day;
                        v_W_S = v_W_S.get_V_W_S_By_Date_And_Dept();
                        wS.Cells[5 + i, colIndex] = v_W_S.Work_rate;
                        if ("休息".Equals(v_W_S.Work_or_rest, StringComparison.OrdinalIgnoreCase))
                        {
                            ((Range)wS.Cells[5 + i, colIndex]).Interior.Color = System.Drawing.Color.Green.ToArgb();
                            continue;
                        }
                        //注意周日为每周的第一天。
                        if ("1" == v_W_S.Day_of_week)
                        {
                            //周日用暗灰色
                            ((Range)wS.Cells[5 + i, colIndex]).Interior.Color = System.Drawing.Color.Yellow.ToArgb();
                        }
                    }
                }
                //自动调整列宽
                //range.EntireColumn.AutoFit();
                //设置禁止弹出保存和覆盖的询问提示框
                app.DisplayAlerts          = false;
                app.AlertBeforeOverwriting = false;
                //保存excel文档并关闭
                wBook.SaveAs(xlsFileFullPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                wBook.Close(true, xlsFileFullPath, Type.Missing);
                //退出Excel程序
                app.Quit();
                //释放资源
                System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wS);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                //调用GC的垃圾收集方法
                GC.Collect();
                GC.WaitForPendingFinalizers();
                msg.Msg     = "工作安排: " + xlsFileFullPath;
                msg.Flag    = true;
                xlsFilePath = xlsFileFullPath;
                return(msg);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示消息:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                msg.Msg     = ex.ToString();
                msg.Flag    = false;
                xlsFilePath = xlsFileFullPath;
                return(msg);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cbPN.Text.Trim()))
            {
                MessageBox.Show("您未选中成衣名称!", "提示:", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //加载图片
            cbPN_SelectedIndexChanged(sender, e);
            if (CmdHelper.ifExistsTheProcessByName("EXCEL") || CmdHelper.ifExistsTheProcessByName("et"))
            {
                Tools.FrmPrompt frmCloseExcel = new Tools.FrmPrompt("excel.exe|et.exe");
                frmCloseExcel.ShowDialog();
            }
            //导出到Excel中
            string _defaultDir = System.Windows.Forms.Application.StartupPath + "\\成本汇总";
            string _fileName   = cbPN.Text.Trim() + "_成本汇总.xls";

            xlsFilePath = FileNameDialog.getSaveFileNameWithDefaultDir("成衣汇总:", "*.xls|*.xls", _defaultDir, _fileName);
            if (!xlsFilePath.Contains(@"\"))
            {
                return;
            }
            //将图片存于粘贴板中。
            Clipboard.SetImage(this.pictureBox.Image);
            System.Data.DataTable dt = (System.Data.DataTable)dgv.DataSource;
            string PN = dt.Rows[0]["成衣名称"].ToString();

            ExcelHelper.saveDtToExcelWithProgressBar((System.Data.DataTable)dgv.DataSource, xlsFilePath, pb);
            MyExcel myExcel = new MyExcel(xlsFilePath);

            myExcel.open();
            Worksheet wS = myExcel.getFirstWorkSheetAfterOpen();


            //获取第二个Sheet.
            myExcel.App.Visible = false;
            Usual_Excel_Helper uEHelper = new Usual_Excel_Helper(wS);
            int maxRowCount             = wS.UsedRange.Rows.Count;

            uEHelper.insertAboveTheSpecificRow(1);
            uEHelper.setSpecificCellValue("A1", PN);
            Range range = (wS.Range)[wS.Cells[2, 2], wS.Cells[maxRowCount, 2]];

            uEHelper.delTheSpecificContentShiftToLeft(range);
            myExcel.App.DisplayAlerts = false;
            uEHelper.merge("A1", "G1");
            uEHelper.MergeTheSpecificColumnWithoutBlankContent(2);

            //保存图片到I1.
            Range rangeI1 = uEHelper.getRange("I1", "I1");

            /*
             *    ActiveSheet.Range("A1").PasteSpecial(
             *   Excel.Enums.XlPasteType.xlPasteAll,
             *   Excel.Enums.Xl‌​PasteSpecialOperation.xlPasteSpecialOperationNone,
             *   false, false);
             */
            rangeI1.Select();
            wS.PasteSpecial();

            //sheet2中写入文件.
            IShowProductsCostSummary iShowProductsCostSummary = new ShowProductsCostSummaryImpl();

            dt = iShowProductsCostSummary.get_P_C_Each_Port(cbPN.Text.Trim());

            //序号, 成衣名称,  概要工序,  指定工序, 指定每部位工序, 工时, 件数, 单价, 最终单价.

            /*
             *  seq_p_c_record,
             *  product_name,
             *  summary_process,
             *  specific_process,
             *  specific_each_process,
             *  man_hours,
             *  amount,
             *  each_cost,
             *  final_labour_cost
             */
            //第二个表格.
            myExcel.AddSheetToLastIndex("每部件成本汇总");
            Worksheet secondWS = myExcel.getSecondWorksheetAfterOpen();

            //先写标题。
            secondWS.Cells[1, 1] = "序号";
            secondWS.Cells[1, 2] = "成衣名称";
            secondWS.Cells[1, 3] = "部位";
            secondWS.Cells[1, 4] = "工序";
            secondWS.Cells[1, 5] = "单部件";
            secondWS.Cells[1, 6] = "单部件_件数";
            //secondWS.Cells[1, 6] = "工时";
            secondWS.Cells[1, 7] = "单部件_工价";
            //secondWS.Cells[1, 7] = "件数";
            secondWS.Cells[1, 8] = "整部位_工时";
            //secondWS.Cells[1, 8] = "单价";
            secondWS.Cells[1, 9]  = "整部位_工价";
            secondWS.Cells[1, 10] = "最终_工价";

            for (int i = 0; i <= dt.Rows.Count - 1; i++)
            {
                secondWS.Cells[2 + i, 1]  = dt.Rows[i]["seq_p_c_record"].ToString();
                secondWS.Cells[2 + i, 2]  = dt.Rows[i]["product_name"].ToString();
                secondWS.Cells[2 + i, 3]  = dt.Rows[i]["summary_process"].ToString();
                secondWS.Cells[2 + i, 4]  = dt.Rows[i]["specific_process"].ToString();
                secondWS.Cells[2 + i, 5]  = dt.Rows[i]["specific_each_process"].ToString();
                secondWS.Cells[2 + i, 6]  = dt.Rows[i]["amount"].ToString();
                secondWS.Cells[2 + i, 7]  = dt.Rows[i]["each_cost"].ToString();
                secondWS.Cells[2 + i, 8]  = dt.Rows[i]["man_hours"].ToString();
                secondWS.Cells[2 + i, 9]  = dt.Rows[i]["labour_cost"].ToString();
                secondWS.Cells[2 + i, 10] = dt.Rows[i]["final_labour_cost"].ToString();
            }
            //获取最终单价的区域.
            Range _range_final_labour_cost;

            uEHelper = new Usual_Excel_Helper(secondWS);
            _range_final_labour_cost = uEHelper.getRange("J2", "J" + secondWS.UsedRange.Rows.Count);
            uEHelper.setFormulaR1C1ForRange(_range_final_labour_cost, "=IF(OR(ISBLANK(RC[-4]),ISBLANK(RC[-3])),RC[-1],RC[-4]*RC[-3])");

            secondWS.UsedRange.EntireColumn.AutoFit();
            myExcel.save();
            myExcel.close();
            //((FrmMainOfProductsCost)this.ParentForm).notifyIcon.ShowBalloonTip(7000, "提示:","汇总保存于: " + xlsFilePath, ToolTipIcon.Info);
            ShowResult.show(lblResult, "汇总保存于: " + xlsFilePath, true);
            timerRestoreLblResult.Start();
        }
        /// <summary>
        ///
        /// </summary>
        private void separateOutputAR()
        {
            string _defaultDir = System.Windows.Forms.Application.StartupPath + "\\考勤汇总";

            killHwndOfXls();
            Queue <int> prefix_Of_Staffs_Queue = V_AR_RESULT.get_Prefix_Staffs(YearAndMonthStr);

            if (prefix_Of_Staffs_Queue.Count == 0)
            {
                ShowResult.show(lblResult, "尚未导入本月的考勤记录!", false);
                timerRestoreTheLblResult.Enabled = true;
                return;
            }
            string prefix_Of_Staffs = string.Empty;

            //分几个工作表储存。
            while (prefix_Of_Staffs_Queue.Count > 0)
            {
                prefix_Of_Staffs = prefix_Of_Staffs_Queue.Dequeue().ToString();
                string _fileName = YearAndMonthStr + "_考勤汇总" + prefix_Of_Staffs.Substring(0, 1) + ".xls";
                if (!xlsFilePath.Contains(":"))
                {
                    //导出到Excel中
                    xlsFilePath = FileNameDialog.getSaveFileNameWithDefaultDir("考勤汇总:", "*.xls|*.xls", _defaultDir, _fileName);
                    if (!xlsFilePath.Contains(@"\"))
                    {
                        return;
                    }
                }
                else
                {
                    int index = xlsFilePath.LastIndexOf(string.Format(@"{0}_考勤汇总", YearAndMonthStr));
                    xlsFilePath = xlsFilePath.Remove(index) + _fileName;
                }
                //int index = xlsFilePath.LastIndexOf(string.Format(@"{0}_考勤汇总", YearAndMonthStr));
                //创建文件
                //DirectoryHelper.createFile(xlsFilePath);
                //xlsFilePath = xlsFilePath.Remove(index) + _fileName;
                MyExcel myExcel = new MyExcel(xlsFilePath);
                myExcel.create();
                myExcel.openWithoutAlerts();
                //追加Hwnd到队列中.
                hwndOfXls_Queue.Enqueue(myExcel.HwndOfApp);
                MSG msg = new MSG();
                //prefix_Of_Staffs = prefix_Of_Staffs_Queue.Dequeue().ToString();
                //依据前缀和月份获取列表。
                //获取第一张表
                Worksheet          _firstWS = myExcel.getFirstWorkSheetAfterOpen();
                Usual_Excel_Helper uEHelper = new Usual_Excel_Helper(_firstWS);
                uEHelper.clearAllContents(_firstWS.UsedRange);
                //清空该文档中的内容。
                Worksheet _secondWS = myExcel.getSecondWorksheetAfterOpen();
                uEHelper = new Usual_Excel_Helper(_secondWS);
                uEHelper.clearAllContents(_secondWS.UsedRange);
                Worksheet _thirdWS = myExcel.getThirdWorksheetAfterOpen();
                uEHelper = new Usual_Excel_Helper(_thirdWS);
                uEHelper.clearAllContents(_thirdWS.UsedRange);
                int machine_no = int.Parse(prefix_Of_Staffs.Substring(0, 1));
                //获取一个月内,某考勤机的考勤天数
                int nums_of_ar_days = GetARSummary.GetARSummary.get_nums_of_ar_days(machine_no, YearAndMonthStr);
                //考勤机的考勤天数
                int nums_of_staffs = GetARSummary.GetARSummary.get_nums_of_staffs(machine_no, YearAndMonthStr);
                System.Data.DataTable dt_Staff_Info       = GetARSummary.GetARSummary.get_Staff_info(YearAndMonthStr, machine_no);
                System.Data.DataTable dt_AR_Of_Each_Staff = GetARSummary.GetARSummary.get_AR_Of_Each_Staff(YearAndMonthStr, machine_no);
                System.Data.DataTable dt_AR_Summary       = GetARSummary.GetARSummary.Get_AR_Summary(YearAndMonthStr, machine_no);
                //隐藏 结果 label;
                lblResult.Visible = false;
                lblPrompt.Visible = true;
                lblPrompt.Text    = "考勤机" + prefix_Of_Staffs.Substring(0, 1) + ": 员工信息汇总中...";
                ExcelHelper.saveDtToExcelWithProgressBar(dt_Staff_Info, _firstWS, pb);
                lblPrompt.Text = "考勤机" + prefix_Of_Staffs.Substring(0, 1) + ": 考勤记录汇总中...";
                ExcelHelper.saveDtToExcelWithProgressBar(dt_AR_Of_Each_Staff, _secondWS, pb);
                lblPrompt.Text = "考勤机" + prefix_Of_Staffs.Substring(0, 1) + ": 汇总中...";
                ExcelHelper.saveDtToExcelWithProgressBar(dt_AR_Summary, _thirdWS, pb);
                Microsoft.Office.Interop.Excel.Range range_Src_AR;
                //目标 区域
                Microsoft.Office.Interop.Excel.Range range_desc_AR;
                //AR_Time 在D列存放
                Usual_Excel_Helper uEHelper_firstWS = new Usual_Excel_Helper(_firstWS);
                for (int i = 1; i <= nums_of_staffs; i++)
                {
                    range_Src_AR = ((Microsoft.Office.Interop.Excel.Range)_secondWS.Range[_secondWS.Cells[(i - 1) * (nums_of_ar_days) + 2, 4], _secondWS.Cells[i * nums_of_ar_days + 1]]);
                    range_Src_AR.Copy();
                    //第一张sheet,第4列
                    range_desc_AR = ((Microsoft.Office.Interop.Excel.Range)_firstWS.Cells[i + 1, 4]);
                    uEHelper_firstWS.pasteByTranspose(range_desc_AR);
                }
                //关闭excel
                myExcel.save();
                myExcel.close();
            }
            lblResult.Visible = true;
            lblPrompt.Visible = false;
        }