using DevExpress.XtraBars.ToolbarForm; using DevExpress.XtraEditors; using DevExpress.XtraGrid.Views.Grid; using DeviceRepair.Models; using DeviceRepair.Models.Common; using DeviceRepair.Models.DeviceRepair.ExportView; using DeviceRepair.Utils; using DeviceRepairAndOptimization.Biz; using DeviceRepairAndOptimization.Common; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; namespace DeviceRepairAndOptimization.Pages.Maintain { public partial class pageMaintainView : ToolbarForm { /// /// 设备编号 /// string Filter_DeviceID { get { return txt_DeviceID.EditValue.ToString().Trim(); } } DeviceWarrantyRequestFormFilter _filter; DeviceWarrantyRequestFormFilter FilterInfo { get { if (_filter == null) _filter = new DeviceWarrantyRequestFormFilter(); _filter.EquipmentID = EquipmentID; if (Filter_Start_Date == DateTime.MinValue) de_StartDate.EditValue = DateTime.Today.AddMonths(-1); _filter.StartTime = Filter_Start_Date; if (Filter_End_Date == DateTime.MinValue) de_EndDate.EditValue = DateTime.Today.AddDays(1).AddMilliseconds(-1); _filter.EndTime = Filter_End_Date.AddDays(1).AddMilliseconds(-1); _filter.Status = Filter_Status; _filter.DownStatus = Filter_DownStatus; return _filter; } } string EquipmentID { get { return txt_DeviceID.Text.Trim(); } } /// /// 设备状态 /// DeviceWarrantyRequestFormStatus Filter_Status { get { return (DeviceWarrantyRequestFormStatus)((int)(cb_Status.EditValue)); } } /// /// 设备停机状态 /// DeviceRunningStatus Filter_DownStatus { get { return (DeviceRunningStatus)cbbIsDown.SelectedIndex; } } /// /// 开始时间 /// DateTime Filter_Start_Date { get { return Convert.ToDateTime(de_StartDate.EditValue); } } /// /// 结束时间 /// DateTime Filter_End_Date { get { return Convert.ToDateTime(de_EndDate.EditValue); } } List lookupMaintenanceStatus; int m_SelectedCurrentRowIndex = 0; DeviceWarrantyRequestFormView CurrentObjectInfo = null; Dictionary _UserMapping; Dictionary UserMapping { get { if (_UserMapping == null) { try { APIResponseData apiResponseData = UserManager.Instance.GetUserMapping(); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); _UserMapping = apiResponseData.ToDeserializeObject>(); } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } return _UserMapping; } } public pageMaintainView() { InitializeComponent(); this.Load += PageMaintainView_Load; } /// /// 程序加载 /// /// /// private void PageMaintainView_Load(object sender, EventArgs e) { //ToDescription if (lookupMaintenanceStatus == null) lookupMaintenanceStatus = new List(); foreach (DeviceWarrantyRequestFormStatus item in Enum.GetValues(typeof(DeviceWarrantyRequestFormStatus))) { lookupMaintenanceStatus.Add(new LookUpItemModel { ValueMember = (int)item, DisplayMember = item.ToDescription() }); } cbbIsDown.Properties.Items.BeginUpdate(); foreach (DeviceRunningStatus item in Enum.GetValues(typeof(DeviceRunningStatus))) { cbbIsDown.Properties.Items.Add(item.ToDescription()); } cbbIsDown.Properties.Items.EndUpdate(); cbbIsDown.SelectedIndex = 0; // 设置显示成员和值成员 layoutControlGroup4.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false; Root.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false; GridViewInitialize(gridView1); cb_Status.Properties.DataSource = lookupMaintenanceStatus; cb_Status.Properties.DisplayMember = "DisplayMember"; cb_Status.Properties.ValueMember = "ValueMember"; cb_Status.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup; cb_Status.EditValue = (int)DeviceWarrantyRequestFormStatus.All; de_StartDate.EditValue = DateTime.Today.AddMonths(-1); de_EndDate.EditValue = DateTime.Today; } List DataSource; /// /// 数据加载 /// void LoadingGridviewDatas() { try { splashScreenManager1.ShowWaitForm(); APIResponseData apiResponseData = MaintenanceManager.Instance.GetDatas(FilterInfo); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); DataSource = apiResponseData.ToDeserializeObject>(); foreach (DeviceWarrantyRequestFormView item in DataSource) { if (string.IsNullOrWhiteSpace(item.CreatorName)) { item.CreatorName = UserMapping.ContainsKey(item.CreatBy.Value) ? UserMapping[item.CreatBy.Value] : ""; } } SizeF size = this.CreateGraphics().MeasureString((DataSource.Count).ToString(), gridView1.Appearance.ViewCaption.Font); gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 25; gridControl1.DataSource = null; gridControl1.DataSource = DataSource.ToDataTable(); //gridView1.BestFitColumns(); splashScreenManager1.TryCloseWait(); } catch (Exception ex) { gridControl1.DataSource = null; splashScreenManager1.TryCloseWait(); XtraMessageBoxHelper.Error(ex.Message); } } /// /// 行选择模式,且全部只读 /// /// void GridViewInitialize(GridView view) { gridView1.OptionsMenu.EnableColumnMenu = false; view.OptionsSelection.EnableAppearanceFocusedCell = false; view.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False; foreach (DevExpress.XtraGrid.Columns.GridColumn item in view.Columns) { item.OptionsColumn.AllowEdit = false; item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True; item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False; item.OptionsColumn.AllowShowHide = false; } view.BestFitColumns(); } /// /// 表格行号 /// /// /// private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle >= 0) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center; SizeF size = e.Graphics.MeasureString((e.RowHandle + 1).ToString(), e.Appearance.Font); } } /// /// 多选框标题修改 /// /// /// private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e) { (new Action(BaseControl.GridControlExtend.CustomDrawColumnHeader)).Invoke(e); } /// /// 单元格点击 /// /// /// private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) { //if (e.Button == MouseButtons.Right) //{ // e.Handled = true; // return; //} //if (e.Column.Caption == "Selection") //{ // if (this.m_SelectedCurrentRowIndex == e.RowHandle && this.gridView1.IsRowSelected(e.RowHandle)) // this.gridView1.UnselectRow(e.RowHandle); //} } /// /// 选择行改变 /// /// /// private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e) { bool WaitIsShowBefore = splashScreenManager1.IsSplashFormVisible; try { if (!WaitIsShowBefore) splashScreenManager1.ShowWaitForm(); if (e.FocusedRowHandle >= 0) { m_SelectedCurrentRowIndex = e.FocusedRowHandle; DataRowView drv = gridView1.GetRow(e.FocusedRowHandle) as DataRowView; string AutoID = drv.Row["AutoID"]?.ToString(); int intAutoID = 0; if (!int.TryParse(AutoID, out intAutoID) && intAutoID <= 0) { throw new Exception("获取行数据出错,请重试!"); } CurrentObjectInfo = DataSource.FirstOrDefault(x => x.AutoID == intAutoID); if (CurrentObjectInfo == null) { throw new Exception("获取行数据出错,请重试!"); } btn_Maintain.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems.SubmitBy == 0 ? true : false; btn_ChangeDownStatus.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems?.SubmitBy == 0 ? true : false; // 双重确认 btn_Validate.Enabled = false; if (CurrentObjectInfo.MaintaionItems != null && CurrentObjectInfo.MaintaionItems.SubmitBy > 0) { // 技术人员确认 if ((GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM1") || GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM2")) && CurrentObjectInfo.MaintaionItems.ValidateBy == 0) { btn_Validate.Enabled = true; btn_Validate.Tag = "1"; }//&& CurrentObjectInfo.MaintaionItems.ValidateBy != GlobalInfo.CurrentUser.AutoID else if (CurrentObjectInfo.MaintaionItems.ValidateBy > 0 && CurrentObjectInfo.MaintaionItems.ValidateBy != GlobalInfo.CurrentUser.AutoID && (GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM2") || GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM3"))) { if (CurrentObjectInfo.MaintaionItems.Validate2By == 0) { btn_Validate.Enabled = true; btn_Validate.Tag = "2"; } } } barBtn_Print.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0; barBtn_ExportWord.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0; barBtn_Print.Refresh(); barBtn_ExportWord.Refresh(); #region 加载表单数据 ucMaintenance view = new ucMaintenance(CurrentObjectInfo); this.splitContainerControl1.Panel2.Controls.Clear(); this.splitContainerControl1.Panel2.Controls.Add(view); view.Show(); this.splitContainerControl1.Panel2.Refresh(); #endregion #region 修改选定状态 //if (gridView1.SelectedRowsCount > 0) //{ // for (int i = 0; i < this.gridView1.RowCount; i++) // { // if (this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false) // { // this.gridView1.UnselectRow(i); // } // } //} this.gridView1.SelectRow(e.FocusedRowHandle); #endregion } else { CurrentObjectInfo = null; } if (!WaitIsShowBefore) splashScreenManager1.CloseWaitForm(); } catch (Exception ex) { if (!WaitIsShowBefore) splashScreenManager1.CloseWaitForm(); //gridView1.FocusedRowChanged += gridView1_FocusedRowChanged; XtraMessageBoxHelper.Error(ex.Message); } } private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e) { GridView view = sender as GridView; view.BeginSelection(); if (e.Action == CollectionChangeAction.Add && view.GetSelectedRows().Length > 1) view.ClearSelection(); if (e.Action == CollectionChangeAction.Refresh) view.SelectRow(view.FocusedRowHandle); if (e.Action == CollectionChangeAction.Remove & view.GetSelectedRows().Length == 0) view.SelectRow(view.FocusedRowHandle); // view.EndSelection(); } /// /// 查询数据 /// /// /// private void btn_Query_Click(object sender, EventArgs e) { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_VIEW")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } LoadingGridviewDatas(); } private void splitContainerControl1_SplitterMoved(object sender, EventArgs e) { this.splitContainerControl1.Panel2.Refresh(); this.splitContainerControl1.Panel1.Refresh(); } private void pageMaintainView_SizeChanged(object sender, EventArgs e) { this.Refresh(); } /// /// 维修 /// /// /// private void btn_Maintain_Click(object sender, EventArgs e) { try { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_EDIT")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { throw new Exception($"请选择要维修的停机单!"); } using (pageMaintainEdit view = new pageMaintainEdit(CurrentObjectInfo)) { if (view.ShowDialog() == DialogResult.OK) { XtraMessageBoxHelper.Info("操作成功!"); } LoadingGridviewDatas(); } } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } /// /// 双重恢复验证 /// /// /// private void btn_Validate_Click(object sender, EventArgs e) { try { if (!GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM1") && !GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM2") && !GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM3")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { throw new Exception($"请选择要操作的停机单!"); } if (XtraMessageBoxHelper.Ask($"是否确认当前设备已恢复!") == DialogResult.OK) { int t = 0; if (!int.TryParse(btn_Validate.Tag + "", out t) && (t != 1 && t != 2)) { throw new Exception($"当前操作员类型获取出错,请重试!"); } APIResponseData apiResponseData = MaintenanceManager.Instance.DoubleValidateMaintenance(CurrentObjectInfo.AutoID, t); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); XtraMessageBoxHelper.Info("操作成功!"); LoadingGridviewDatas(); } } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } /// /// 修改停机状态 /// /// /// private void btn_ChangeDownStatus_Click(object sender, EventArgs e) { try { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_EDIT")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { throw new Exception($"请选择要维修的停机单!"); } if (XtraMessageBoxHelper.Ask($"是否确认将维修单:{CurrentObjectInfo.AutoID}的停机状态修改为:{(CurrentObjectInfo.IsDown ? "非停机" : "停机")}状态!") == DialogResult.OK) { APIResponseData apiResponseData = MaintenanceManager.Instance.ChangeDownStatus(CurrentObjectInfo.AutoID, !CurrentObjectInfo.IsDown); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); XtraMessageBoxHelper.Info("操作成功!"); LoadingGridviewDatas(); } } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } /// /// 打印 /// /// /// private void simpleButton1_Click(object sender, EventArgs e) { try { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_PRINT")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { throw new Exception("获取对象失败,请重试!"); } DataTable table = SubassembliesCurrentData(); FastReport.Report report = new FastReport.Report(); var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels"); //判断文件夹是否存在 if (!System.IO.Directory.Exists(vLabelDir)) { throw new Exception("缺少待打印的标签模板目录!"); } //路径拼接模板文件名 var vFileName = System.IO.Path.Combine(vLabelDir, "DeviceMaintenance.frx"); //判断模板文件是否存在 if (!System.IO.File.Exists(vFileName)) { throw new Exception("缺少待打印的标签模板文件!"); } report.Load(vFileName); report.DoublePass = true; DataSet dsDatas = new DataSet(); dsDatas.Tables.Add(table); report.RegisterData(dsDatas, "MaintenanceInfo"); //report.Design(); if (report.Prepare(true)) { report.ShowPrepared(); } report.Dispose(); } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } private DataTable SubassembliesCurrentData() { DataTable table = new DataTable("MaintenanceInfo"); table.Columns.Add("申请部门", typeof(string)); table.Columns.Add("名称", typeof(string)); table.Columns.Add("设备编号", typeof(string)); table.Columns.Add("接收部门", typeof(string)); table.Columns.Add("现象区分", typeof(string)); table.Columns.Add("故障发生地点", typeof(string)); table.Columns.Add("故障发生时间", typeof(string)); table.Columns.Add("维修方式", typeof(string)); table.Columns.Add("产品批号", typeof(string)); table.Columns.Add("修理开始日期", typeof(string)); table.Columns.Add("修理结束日期", typeof(string)); table.Columns.Add("质量部评估", typeof(string)); table.Columns.Add("工程部评估", typeof(string)); table.Columns.Add("总修复时间", typeof(string)); table.Columns.Add("总停机时间", typeof(string)); table.Columns.Add("故障现象", typeof(string)); table.Columns.Add("故障原因", typeof(string)); table.Columns.Add("维修内容", typeof(string)); table.Columns.Add("配件", typeof(string)); table.Columns.Add("人员", typeof(string)); table.Columns.Add("是否需要再验证", typeof(string)); table.Columns.Add("验证编号", typeof(string)); table.Columns.Add("设备恢复确认", typeof(string)); table.Columns.Add("申请部门确认/日期", typeof(string)); APIResponseData apiResponseData = FieldsManager.Instance.GetQuery("SymptomlDistinction,Maintenance,Accessories"); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); List SelectionDatas = apiResponseData.ToDeserializeObject>(); Dictionary keyValuePairs = SelectionDatas.ToDictionary(x => x.AutoID, x => x); DataRow dr = table.NewRow(); dr["申请部门"] = $"生产部 - {CurrentObjectInfo.CreatorName}"; dr["名称"] = CurrentObjectInfo.EquipmentName; dr["设备编号"] = CurrentObjectInfo.EquipmentID; dr["接收部门"] = "设备实施部"; dr["现象区分"] = keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.SymptomlDistinction) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.SymptomlDistinction].FieldText : ""; dr["故障发生地点"] = CurrentObjectInfo.LocationName; dr["故障发生时间"] = CurrentObjectInfo.CreatOn.Value.ToString("yyyy-MM-dd HH:mm:ss"); dr["维修方式"] = keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.Maintenance) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.Maintenance].FieldText : ""; dr["产品批号"] = CurrentObjectInfo.InProduction ? $@"Yes, Product Lot/Testing Order产品批号/检测任务号{Environment.NewLine}{CurrentObjectInfo.Batch}" : "No"; dr["修理开始日期"] = CurrentObjectInfo.MaintaionItems.MaintainStartTime.ToString("yyyy-MM-dd HH:mm:ss"); dr["修理结束日期"] = CurrentObjectInfo.MaintaionItems.MaintainEndTime.ToString("yyyy-MM-dd HH:mm:ss"); if (CurrentObjectInfo.EvaluatorItems != null && CurrentObjectInfo.EvaluatorItems.Count > 0) { var PEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "PE").FirstOrDefault(); if (PEItem != null) { dr["质量部评估"] = $"{PEItem.Description} - {PEItem.CreatorName}"; } var QEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "QE").FirstOrDefault(); if (QEItem != null) { dr["工程部评估"] = $"{QEItem.Description} - {QEItem.CreatorName}"; } } else { dr["质量部评估"] = "N/A"; dr["工程部评估"] = "N/A"; } DateTime FormSubDate = CurrentObjectInfo.CreatOn.Value; TimeSpan timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - CurrentObjectInfo.MaintaionItems.MaintainStartTime; dr["总修复时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒"; timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - FormSubDate; dr["总停机时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒"; dr["故障现象"] = CurrentObjectInfo.FaultSymptoms; dr["故障原因"] = CurrentObjectInfo.MaintaionItems.MaintainCause; dr["维修内容"] = CurrentObjectInfo.MaintaionItems.MaintainContent; //配件 if (CurrentObjectInfo.MaintaionItems.AccessoriesItems != null && CurrentObjectInfo.MaintaionItems.AccessoriesItems.Count > 0) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (DeviceWarrantyRequestAccessoriesInfo item in CurrentObjectInfo.MaintaionItems.AccessoriesItems) { builder.Append($"{item.FieldName} x {item.AccessoriesCount};"); } dr["配件"] = builder.ToString(); } dr["人员"] = UserMapping[CurrentObjectInfo.MaintaionItems.SubmitBy]; if (CurrentObjectInfo.MaintaionItems.BeValidate) { dr["是否需要再验证"] = $"Yes 需要,Validation ID验证编号:{CurrentObjectInfo.MaintaionItems.ValidateNo}"; } else { dr["是否需要再验证"] = $"No 不需要, Rational理由:{CurrentObjectInfo.MaintaionItems.Reason}"; } dr["验证编号"] = ""; string doubleValidate = ""; if (CurrentObjectInfo.MaintaionItems.ValidateBy == 0) { doubleValidate = "N/A"; } else { doubleValidate = $"{UserMapping[CurrentObjectInfo.MaintaionItems.ValidateBy]} / {CurrentObjectInfo.MaintaionItems.ValidateOn.ToString("yyyy-MM-dd HH:mm:ss")}"; if (CurrentObjectInfo.MaintaionItems.Validate2By == 0) { doubleValidate += " N/A"; } else { doubleValidate += $" {UserMapping[CurrentObjectInfo.MaintaionItems.Validate2By]} / {CurrentObjectInfo.MaintaionItems.Validate2On.ToString("yyyy-MM-dd HH:mm:ss")}"; } } dr["设备恢复确认"] = doubleValidate; dr["申请部门确认/日期"] = $"{CurrentObjectInfo.RestorationConfirmationOnName} / { CurrentObjectInfo.RestorationConfirmationOn.Value.ToString("yyyy-MM-dd HH:mm:ss")}"; table.Rows.Add(dr); return table; } /// /// 打印 /// /// /// private void barBtn_Print_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { this.barBtn_Print.Enabled = false; try { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_PRINT")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { barBtn_Print.Enabled = false; barBtn_Print.Refresh(); throw new Exception("请选择要打印的维修单!"); } DataTable table = SubassembliesCurrentData(); FastReport.Report report = new FastReport.Report(); var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels"); //判断文件夹是否存在 if (!System.IO.Directory.Exists(vLabelDir)) { throw new Exception("缺少待打印的标签模板目录!"); } //路径拼接模板文件名 var vFileName = System.IO.Path.Combine(vLabelDir, "DeviceMaintenance.frx"); //判断模板文件是否存在 if (!System.IO.File.Exists(vFileName)) { throw new Exception("缺少待打印的标签模板文件!"); } report.Load(vFileName); report.DoublePass = true; DataSet dsDatas = new DataSet(); dsDatas.Tables.Add(table); report.RegisterData(dsDatas, "MaintenanceInfo"); //report.Design(); if (report.Prepare(true)) { report.ShowPrepared(); } report.Dispose(); } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } this.barBtn_Print.Enabled = true; } /// /// 导出word /// /// /// private void barBtn_ExportWord_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { try { if (!GlobalInfo.HasRole("BIZ_REPAIRRECORD_EXPORT")) { XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限"); return; } if (CurrentObjectInfo == null) { barBtn_ExportWord.Enabled = false; barBtn_ExportWord.Refresh(); throw new Exception("请选择要导出的维修单!"); } using (FolderBrowserDialog folderDialog = new FolderBrowserDialog()) { folderDialog.Description = "请选择保存文件的路径:"; folderDialog.ShowNewFolderButton = true; DialogResult result = folderDialog.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath)) { string selectedPath = folderDialog.SelectedPath; DataTable table = SubassembliesCurrentData(); FastReport.Report report = new FastReport.Report(); var vLabelDir = Path.Combine(Application.StartupPath, "Labels"); //判断文件夹是否存在 if (!Directory.Exists(vLabelDir)) { throw new Exception("缺少待打印的标签模板目录!"); } //路径拼接模板文件名 var vFileName = Path.Combine(vLabelDir, "DeviceMaintenance.frx"); //判断模板文件是否存在 if (!File.Exists(vFileName)) { throw new Exception("缺少待打印的标签模板文件!"); } report.Load(vFileName); report.DoublePass = true; DataSet dsDatas = new DataSet(); dsDatas.Tables.Add(table); report.RegisterData(dsDatas, "MaintenanceInfo"); string filePath = Path.Combine(selectedPath, ("维修单" + CurrentObjectInfo.AutoID + ".docx")); if (report.Prepare()) { FastReport.Export.OoXML.Word2007Export export = new FastReport.Export.OoXML.Word2007Export(); report.MaxPages = 1; export.CurPage = 1; report.Export(export, filePath); } report.Dispose(); XtraMessageBoxHelper.Info($"导出成功!"); } } } catch (Exception ex) { XtraMessageBoxHelper.Error(ex.Message); } } private void barBtnExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { try { splashScreenManager1.ShowWaitForm(); APIResponseData apiResponseData = MaintenanceManager.Instance.GetXlsxData(FilterInfo); if (!apiResponseData.IsSuccess) throw new Exception(apiResponseData.Message); List views = apiResponseData.ToDeserializeObject>(); DataTable dataTable = views.ToDataTable(); System.Reflection.PropertyInfo[] prop = typeof(MaintainOrderView).GetProperties(); foreach (System.Reflection.PropertyInfo item in prop) { if (dataTable.Columns.Contains(item.Name)) { DataColumn dc = dataTable.Columns[item.Name]; object[] attrs = item.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (null != attrs && attrs.Length > 0) { System.ComponentModel.DescriptionAttribute description = (System.ComponentModel.DescriptionAttribute)attrs[0]; dc.ColumnName = description.Description; } } } splashScreenManager1.TryCloseWait(); XtraSaveFileDialog xofd = new XtraSaveFileDialog() { Filter = "xlsx file(*.xlsx)|*.xlsx" }; SelectPath: if (xofd.ShowDialog() == DialogResult.OK) { if (File.Exists(xofd.FileName)) { XtraMessageBoxHelper.Error("当前文件已存在,请重新命名!"); goto SelectPath; } byte[] btRtn = Export(dataTable); Common.dlgProgressBar view = new Common.dlgProgressBar(btRtn, xofd.FileName); view.ShowDialog(); XtraMessageBoxHelper.Info("操作成功!"); } } catch (Exception ex) { splashScreenManager1.TryCloseWait(); XtraMessageBoxHelper.Error(ex.Message); } } byte[] Export(DataTable dataTable) { try { IWorkbook workbook = new XSSFWorkbook(); string sheetName = string.IsNullOrEmpty(dataTable.TableName) ? "Sheet1" : dataTable.TableName; ISheet sheet = workbook.CreateSheet(sheetName); // 创建表头 IRow headerRow = sheet.CreateRow(0); // 表头样式 #region 表头样式 ICellStyle style = workbook.CreateCellStyle(); style.WrapText = true;//设置换行这个要先设置 style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中 style.VerticalAlignment = VerticalAlignment.Center;//水平居中 //HSSFPalette palette = new HSSFPalette(); //palette.SetColorAtIndex((short)1, 217, 217, 217); //var v1 = palette.FindColor(217, 217, 217); //colorStyle.FillForegroundColor = v1.GetIndex(); style.FillPattern = FillPattern.SolidForeground; style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中 cellStyle.VerticalAlignment = VerticalAlignment.Center;//水平居中 cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; ////设置字体 //IFont font = workbook.CreateFont(); //font.FontHeightInPoints = 10; //font.FontName = "黑体"; //style.SetFont(font); #endregion for (int i = 0; i < dataTable.Columns.Count; i++) { headerRow.CreateCell(i).SetCellValue(dataTable.Columns[i].ColumnName); headerRow.GetCell(i).CellStyle = style; headerRow.GetCell(i).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium; headerRow.GetCell(i).CellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium; headerRow.GetCell(i).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium; headerRow.GetCell(i).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium; } // 填充数据 for (int i = 0; i < dataTable.Rows.Count; i++) { IRow dataRow = sheet.CreateRow(i + 1); for (int j = 0; j < dataTable.Columns.Count; j++) { dataRow.CreateCell(j).SetCellValue(dataTable.Rows[i][j].ToString()); ICellStyle styleContent = workbook.CreateCellStyle(); styleContent.CloneStyleFrom(cellStyle); dataRow.GetCell(j).CellStyle = styleContent; // 第一列 if (j == 0) dataRow.GetCell(j).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium; else if (j == dataTable.Columns.Count - 1) { // 最后一列 dataRow.GetCell(j).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium; } if (i == dataTable.Rows.Count - 1) dataRow.GetCell(j).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium; } } for (int i = 0; i < dataTable.Columns.Count; i++) { sheet.AutoSizeColumn(i); } // 转换为byte[] using (MemoryStream stream = new MemoryStream()) { workbook.Write(stream); return stream.ToArray(); } } catch (Exception ex) { throw new Exception($"生成EXCEL出错:{ex.Message}"); } } } }