Application.Title在Win7下失效了?

本文介绍如何在Delphi XE中设置自定义的应用程序标题而非默认使用MainForm的Caption。通过设置Application.MainFormOnTaskbar属性为False并指定Application.Title属性可以实现这一目的。

Delphi XE会默认使用Mainform的Caption作为Application的title,就是你在任务栏上看到的标题。实际上这是为兼容Vista设计的,如果你要显示自定义的标题,需要修改项目文件, 

begin
  Application.Initialize;
  Application.MainFormOnTaskbar := False; //otherwise will use mainform caption on task bar
  Application.Title := 'Default Title';
  Application.CreateForm(TMainForm, MainForm);
  Application.Run;
end.


MainFormOnTaskbar是Application对象新增加的属性,默认是True。

import tkinter as tk import requests import base64 from tkinter import filedialog as fil from PIL import Image,ImageTk from debugpy.adapter import access_token win=tk.Tk() win.title("title") win.geometry("400x600+200+100") win.configure(bg="gray") win.title("🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟🐟") def get_pic(): global path path=fil.askopenfilename() try: img=Image.open(path).resize((370,250)) img=ImageTk.PhotoImage(img) l1.image=img l1.configure(image=img) except AttributeError: t1.delete("0.0","end") t1.insert("end","请选择图片") def shibie(): t1.delete("0.0","end") t1.insert("insert", "正在识别……") requests_url='https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting' try: f=open(path,"rb") img=base64.b64encode(f.read()) params={"image":img} access_token=get_access() requests_url=requests_url+"?access_token="+access_token headers={'content-type':'application/x-www-from-urlencoded'} response=requests.post(requests_url,data=params,headers=headers) if response: result=response.json() t1.delete("0.0","end") for words in result["words_result"]: t1.insert("end",words['words']+"\n") except NameError: t1.delete("0.0", "end") t1.insert("end", "请选择图片") def get_access(): host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&' \ 'client_id=uZ3TtAkfe3Andj4Gflo7KyBT&' \ 'client_secret=Qr17kCrG1hMZqZO5Lk2LN5BZGNk9cfGB' response=requests.get(host) if response: d1=response.json() return d1['access_token'] def save(): pass l1=tk.Label(win,height=14,width=48,font=("微软雅黑",10)) l1.place(x=5,y=5) t1=tk.Text(win,height=12,width=48,font=("微软雅黑",10)) t1.place(x=6,y=280) ins=""" 🐟使用方法🐟: 🐟点击选择图片,选择需要识别的图片\n 🐟点击开始识别,识别出图片中的文字\n 🐟调整识别出的文字后,点击保存文本 """ t1.insert("end",ins) b1=tk.Button(win,text="🐟图片选择🐟",font=("微软雅黑",10),command=get_pic) b1.place(x=25,y=540) b2=tk.Button(win,text="🐟识别文字🐟",font=("微软雅黑",10),command=shibie) b2.place(x=150,y=540) b3=tk.Button(win,text="🐟文本保存🐟",font=("微软雅黑",10))#,command=pass) b3.place(x=275,y=540) win.mainloop() 为什么图片显示不了
08-20
<!--由代码生成工具生成--> <UserControl x:Class="MES.Client.Tooling.UserControls.ModifyMeasuringFaliureTracing" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:hc="https://handyorg.github.io/handycontrol" xmlns:local="clr-namespace:MES.Client.Tooling.UserControls" xmlns:hc1="clr-namespace:Minio.DataModel;assembly=Minio" d:DataContext="{d:DesignInstance Type=local:ModifyMeasuringFaliureTracingViewModel}" mc:Ignorable="d" d:DesignHeight="350" d:DesignWidth="600"> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/MES.Client.UICommon;component/Styles/CommStyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> <hc:DialogContainer> <Border CornerRadius="3" Background="{DynamicResource DialogPrimaryBrush}"> <Grid TextBlock.Foreground="{DynamicResource DefaultFontColorBrush}"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <!--标题--> <Border CornerRadius="4 4 0 0" Background="{DynamicResource DialogTitleBrush}" BorderThickness="0" TextBlock.Foreground="{DynamicResource DefaultFontColorBrush}"> <Grid Margin="0 10"> <TextBlock Text="{Binding Title,FallbackValue=量具失效追溯管理}" FontWeight="SemiBold" FontSize="14" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="20 0 0 0"/> <Button Style="{StaticResource CloseButtonStyle}"/> </Grid> </Border> <!--表单--> <Grid Grid.Row="1" Margin="0 10"> <ScrollViewer VerticalScrollBarVisibility="Auto"> <!-- 允许垂直滚动 --> <UniformGrid Columns="1"> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[ToolCode],FallbackValue=ToolCode}" VerticalAlignment="Center" Text="{Binding SelectData.ToolCode}" hc:InfoElement.Necessary="True"/> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[DeviceName],FallbackValue=DeviceName}" VerticalAlignment="Center" Text="{Binding SelectData.DeviceName}" hc:InfoElement.Necessary="True"/> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[Manufacturer],FallbackValue=Manufacturer}" VerticalAlignment="Center" Text="{Binding SelectData.Manufacturer}"/> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[ModelSpec],FallbackValue=ModelSpec}" VerticalAlignment="Center" Text="{Binding SelectData.ModelSpec}"/> <hc:DateTimePicker hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[FailureDate],FallbackValue=FailureDate}" VerticalAlignment="Center" SelectedDateTime="{Binding SelectData.FailureDate}" hc:InfoElement.Necessary="True"/> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[FailurePhenomenon],FallbackValue=FailurePhenomenon}" VerticalAlignment="Center" Text="{Binding SelectData.FailurePhenomenon}" /> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[IsInvolveProduct],FallbackValue=IsInvolveProduct}" VerticalAlignment="Center" Text="{Binding SelectData.IsInvolveProduct}" /> <hc:TextBox hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" Margin="10 0 10 10" hc:InfoElement.Title="{Binding Langs[Remark],FallbackValue=Remark}" VerticalAlignment="Center" Text="{Binding SelectData.Remark}"/> <hc:Upload hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Title="{Binding Langs[ProcessingRecords],FallbackValue=失效产品处理记录}" FileType="*" MaxCount="5" UploadUrl="{Binding UploadUrl}" Files="{Binding SelectData.ProcessingRecords, Mode=TwoWay}" hc:InfoElement.Placeholder="{Binding Langs[UploadTip],FallbackValue=处理记录请自行上传}"/> </UniformGrid> </ScrollViewer> </Grid> <DockPanel Grid.Row="2" Margin="13 0"> <Button Margin="10" Width="130" Background="{DynamicResource AddBtnBrush}" Foreground="White" BorderBrush="{DynamicResource AddBtnBrush}" Content="{Binding Langs[Confirm]}" DockPanel.Dock="Right" HorizontalAlignment="Right" Command="{Binding SaveCommand}"/> <Button Margin="10" Width="130" Content="{Binding Langs[Cancel]}" DockPanel.Dock="Right" HorizontalAlignment="Right" Command="hc:ControlCommands.Close"/> </DockPanel> </Grid> </Border> </hc:DialogContainer> </UserControl> <UserControl x:Class="MES.Client.Tooling.UserControls.MeasuringFaliureTracing" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:hc="https://handyorg.github.io/handycontrol" xmlns:control="clr-namespace:MES.Client.UICommon.Controls;assembly=MES.Client.UICommon" hc:Dialog.Token="{Binding DialogToken}" d:DataContext="{d:DesignInstance Type=usercontrols:MeasuringFaliureTracingViewModel,IsDesignTimeCreatable=True}" xmlns:enum="clr-namespace:MES.Client.Toolkit.Enums;assembly=MES.Client.Toolkit" xmlns:usercontrols="clr-namespace:MES.Client.Tooling.UserControls" xmlns:sync="http://schemas.syncfusion.com/wpf" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <UserControl.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/MES.Client.UICommon;component/Styles/CommStyle.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </UserControl.Resources> <hc:DialogContainer> <Grid Background="{DynamicResource MESPrimaryBrush}"> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition/> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal" Margin="10"> <TextBlock Text="量具失效追溯管理" FontWeight="DemiBold" VerticalAlignment="Center" FontSize="16" Margin="21 0 0 0"/> <Border BorderThickness="1 0 0 0" BorderBrush="{DynamicResource MESBorderBrush}" Margin="20 0" Height="24"/> <control:IconButton Visibility="{Binding MenuID,Converter={StaticResource getPermissonToVisibilityConverter},ConverterParameter={x:Static enum:PermissonEnum.Add }}" IBForeground="{DynamicResource PaginationSelectedBrush}" Background="{DynamicResource AddBtnBrush}" StrText="{Binding Langs[Add]}" Icon="" BorderThickness="0" FontSize="14" Margin="0 0 10 0" Command="{Binding ModifyCommand}"/> </StackPanel> <hc:Card Grid.Row="1" Margin="10 0 10 10" BorderThickness="1"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <DockPanel TextBlock.FontSize="14"> <hc:TextBox Margin="13" hc:InfoElement.Title="{Binding Langs[ToolCode],FallbackValue=ToolCode}" Text="{Binding SearchData.ToolCode}" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" hc:InfoElement.TitlePlacement="Left" HorizontalAlignment="Left" Width="150"/> <hc:TextBox Margin="13" hc:InfoElement.Title="{Binding Langs[DeviceName],FallbackValue=DeviceName}" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}" hc:InfoElement.TitlePlacement="Left" Width="150" Text="{Binding SearchData.DeviceName}"/> <hc:DateTimePicker Margin="13" SelectedDateTime ="{Binding SearchData.StartFailureDate}" Style="{StaticResource DateTimePickerPlus}" hc:InfoElement.Title="{Binding Langs[StartFailureDate],FallbackValue=StartFailureDate}" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}"/> <hc:DateTimePicker Margin="13" SelectedDateTime="{Binding SearchData.EndFailureDate}" Style="{StaticResource DateTimePickerPlus}" hc:InfoElement.Title="{Binding Langs[EndFailureDate],FallbackValue=EndFailureDate}" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Placeholder="{Binding Langs[PleaseEnter]}"/> <control:IconButton Visibility="{Binding MenuID,Converter={StaticResource getPermissonToVisibilityConverter},ConverterParameter={x:Static enum:PermissonEnum.Query }}" StrText="{Binding Langs[Search]}" Icon="" FontSize="14" HorizontalAlignment="Left" Margin="32 0 0 0" Command="{Binding SearchCommand}"/> </DockPanel> <control:MESSfDataGrid SelectedItems="{Binding SelectedItems,Mode=TwoWay}" SelectionMode="Extended" IsShowChooseBtn="True" MenuID="{Binding MenuID}" Token="{Binding DialogToken}" Margin="10 0 10 5" ItemsSource="{Binding DataList}" Grid.Row="1" Langs="{Binding Langs}" EditCommand="{Binding ModifyCommand}" DeleteCommand="{Binding DeleteCommand}" ImportCommand="{Binding SearchCommand}" SolTypeName="VENDOR" IsImport="{Binding MenuID,Converter={StaticResource getPermissonToBoolConverter},ConverterParameter={x:Static enum:PermissonEnum.Import }}" IsDel="{Binding MenuID,Converter={StaticResource getPermissonToBoolConverter},ConverterParameter={x:Static enum:PermissonEnum.Delete }}" IsEdit="{Binding MenuID,Converter={StaticResource getPermissonToBoolConverter},ConverterParameter={x:Static enum:PermissonEnum.Modify }}" IsDetail="False"> <control:MESSfDataGrid.Columns> <sync:GridTextColumn MappingName="Id" HeaderText="{Binding Langs[Id],FallbackValue=Id}" IsHidden="True"/> <sync:GridTextColumn MappingName="ItemNo" HeaderText="{Binding Langs[ItemNo],FallbackValue=ItemNo}" IsHidden="True"/> <sync:GridTextColumn MappingName="ToolCode" HeaderText="{Binding Langs[ToolCode],FallbackValue=ToolCode}" IsHidden="False"/> <sync:GridTextColumn MappingName="DeviceName" HeaderText="{Binding Langs[DeviceName],FallbackValue=DeviceName}" IsHidden="False"/> <sync:GridTextColumn MappingName="Manufacturer" HeaderText="{Binding Langs[Manufacturer],FallbackValue=Manufacturer}" IsHidden="False"/> <sync:GridTextColumn MappingName="ModelSpec" HeaderText="{Binding Langs[ModelSpec],FallbackValue=ModelSpec}" IsHidden="False"/> <sync:GridDateTimeColumn CustomPattern="yyyy-MM-dd HH:mm:ss" Pattern="CustomPattern" MappingName="FailureDate" HeaderText="{Binding Langs[FailureDate],FallbackValue=FailureDate}" IsHidden="False"/> <sync:GridTextColumn MappingName="FailurePhenomenon" HeaderText="{Binding Langs[FailurePhenomenon],FallbackValue=FailurePhenomenon}" IsHidden="False"/> <sync:GridTextColumn MappingName="IsInvolveProduct" HeaderText="{Binding Langs[IsInvolveProduct],FallbackValue=IsInvolveProduct}" IsHidden="False"/> <!--失效产品处理记录--> <!-- 在现有列后追加 --> <sync:GridTextColumn MappingName="ProcessingRecords" HeaderText="{Binding Langs[ProcessingRecords],FallbackValue=失效产品处理记录}" IsHidden="False"/> <sync:GridTextColumn MappingName="Remark" HeaderText="{Binding Langs[Remark],FallbackValue=Remark}" IsHidden="False"/> <!-- <sync:GridDateTimeColumn CustomPattern="yyyy-MM-dd HH:mm:ss" Pattern="CustomPattern" MappingName="CreateTime" HeaderText="{Binding Langs[CreateTime],FallbackValue=CreateTime}" IsHidden="True"/> <sync:GridTextColumn MappingName="CreateUser" HeaderText="{Binding Langs[CreateUser],FallbackValue=CreateUser}" IsHidden="False"/> <sync:GridDateTimeColumn CustomPattern="yyyy-MM-dd HH:mm:ss" Pattern="CustomPattern" MappingName="UpdateTime" HeaderText="{Binding Langs[UpdateTime],FallbackValue=UpdateTime}" IsHidden="True"/> <sync:GridTextColumn MappingName="UpdateUser" HeaderText="{Binding Langs[UpdateUser],FallbackValue=UpdateUser}" IsHidden="True"/>--> </control:MESSfDataGrid.Columns> </control:MESSfDataGrid> <control:YLHPagination Margin="10 5" Grid.Row="2" PageIndex="{Binding PageIndex,Mode=TwoWay}" TotalCount="{Binding TotalCount}" PageSize="{Binding PageSize,Mode=TwoWay}" TotalPages="{Binding TotalPages,Mode=TwoWay}"/> </Grid> </hc:Card> </Grid> </hc:DialogContainer> </UserControl>修改里面的上传文件那块代码 <hc:Upload hc:InfoElement.TitlePlacement="Left" hc:InfoElement.TitleWidth="100" hc:InfoElement.Title="{Binding Langs[ProcessingRecords],FallbackValue=失效产品处理记录}" FileType="*" MaxCount="5" UploadUrl="{Binding UploadUrl}" Files="{Binding SelectData.ProcessingRecords, Mode=TwoWay}" hc:InfoElement.Placeholder="{Binding Langs[UploadTip],FallbackValue=处理记录请自行上传}"/>using HandyControl.Tools.Extension; using MES.Client.Tooling.Models.MeasuringFaliureTracing; using MES.Client.Toolkit.Comm; using MES.Client.Toolkit.Enums; using MES.Client.Toolkit.HTTP; using MES.Client.UICommon.Controls; using MES.Common.Toolkit.Helper; using System; using System.Collections.Generic; using System.Text; using System.Windows.Controls; using System.Windows.Input; namespace MES.Client.Tooling.UserControls { /// <summary> /// ModifyMeasuringFaliureTracing.xaml 的交互逻辑 /// </summary> public partial class ModifyMeasuringFaliureTracing : UserControl { public ModifyMeasuringFaliureTracing(MeasuringFailureTracingModel masModel, Dictionary<string, string> langs, OperateStateEmun stateEmun) { InitializeComponent(); DataContext = new ModifyMeasuringFaliureTracingViewModel(masModel, langs, stateEmun); } } public class ModifyMeasuringFaliureTracingViewModel : ViewModelBase, IDialogResultable<bool> { private MeasuringFailureTracingModel selectData = new(); private Dictionary<string, string> langs = new(); private string title = string.Empty; public string UploadUrl { get; set; } = "api/Tooling/MeasuringFaliureTracing/UnLoad"; public string ProcessingRecords { get; set; } = string.Empty; public MeasuringFailureTracingModel SelectData { get => selectData; set { selectData = value; PCEH(); } } public Dictionary<string, string> Langs { get => langs; set { langs = value; PCEH(); } } public bool Result { get; set; } = false; public Action? CloseAction { get; set; } /// <summary> /// 保存 /// </summary> public ICommand SaveCommand { get; set; } public string Title { get => title; set { title = value; PCEH(); } } /// <summary> /// 操作类型 /// </summary> public OperateStateEmun StateEmun { get; set; } public ModifyMeasuringFaliureTracingViewModel(MeasuringFailureTracingModel itemtModel, Dictionary<string, string> langs, OperateStateEmun stateEmun) { StateEmun = stateEmun; SelectData = itemtModel.Clone(); //if (stateEmun == OperateStateEmun.Add) //{ // SelectData.LastAnalysisDate ??= DateTime.Today.AddDays(-30); // SelectData.NextRemindDate ??= DateTime.Today.AddDays(30); //} Langs = langs; Initialize(); SaveCommand = new CommandBase(async l => { if (!Check()) return; string ret = string.Empty; int toolCodeLength = getStringLength(SelectData.ToolCode); if (toolCodeLength > 40) { Message.Warnning(Langs.LangGetValue("ToolCode") + Langs.LangGetValue("CharacterLengthIsLong")); return; } int deviceNameLength = getStringLength(SelectData.DeviceName); if (deviceNameLength > 40) { Message.Warnning(Langs.LangGetValue("DeviceName") + Langs.LangGetValue("CharacterLengthIsLong")); return; } if (!string.IsNullOrEmpty(SelectData.Manufacturer)) { int manufacturerLength = getStringLength(SelectData.Manufacturer); if (manufacturerLength > 40) { Message.Warnning(Langs.LangGetValue("Manufacturer") + Langs.LangGetValue("CharacterLengthIsLong")); return; } } if (!string.IsNullOrEmpty(SelectData.ModelSpec)) { int modelSpecLength = getStringLength(SelectData.ModelSpec); if (modelSpecLength > 100) { Message.Warnning(Langs.LangGetValue("ModelSpec") + Langs.LangGetValue("CharacterLengthIsLong")); return; } } if (!string.IsNullOrEmpty(SelectData.FailurePhenomenon)) { int failurePhenomenonLength = getStringLength(SelectData.FailurePhenomenon); if (failurePhenomenonLength > 200) { Message.Warnning(Langs.LangGetValue("FailurePhenomenon") + Langs.LangGetValue("CharacterLengthIsLong")); return; } } if (!string.IsNullOrEmpty(SelectData.IsInvolveProduct)) { int isInvolveProductLength = getStringLength(SelectData.IsInvolveProduct); if (isInvolveProductLength > 1) { Message.Warnning(Langs.LangGetValue("IsInvolveProduct") + Langs.LangGetValue("CharacterLengthIsLong")); return; } } if (!string.IsNullOrEmpty(SelectData.Remark)) { int remarkLength = getStringLength(SelectData.Remark); if (remarkLength > 300) { Message.Warnning(Langs.LangGetValue("Remark") + Langs.LangGetValue("CharacterLengthIsLong")); return; } } ret = await APIHelper.PostSendAsync(ApiRoutes.SaveMeasuringFaliureTracing, SelectData); if (ret is not null) { string successMsg = StateEmun == OperateStateEmun.Add ? Langs.LangGetValue("添加成功") : Langs.LangGetValue("修改成功"); MESGrowl.MESSuccess(successMsg); Result = true; CloseAction?.Invoke(); } }); } public int getStringLength(string str) { if (str.Equals(string.Empty)) return 0; int strlen = 0; ASCIIEncoding strData = new ASCIIEncoding(); // 将字符串转换为ASCII编码的字节数字 byte[] strBytes = strData.GetBytes(str); for (int i = 0; i <= strBytes.Length - 1; i++) { if (strBytes[i] == 63) // 中文都将编码为ASCII编码63,即"?"号 strlen += 2; strlen++; } return strlen; } private bool Check() { if (string.IsNullOrEmpty(SelectData.ToolCode)) { Message.Warnning(Langs.LangGetValue("ToolCode") + Langs.LangGetValue("IsInvalid")); return false; } // 检查DeviceName(设备名称)是否为空 if (string.IsNullOrEmpty(SelectData.DeviceName)) { Message.Warnning(Langs.LangGetValue("DeviceName") + Langs.LangGetValue("IsNull")); return false; } //// 检查LastAnalysisDate(上次分析日期)是否有值 //if (!SelectData.LastAnalysisDate.HasValue) //{ // Message.Warnning(Langs.LangGetValue("LastAnalysisDate") + Langs.LangGetValue("IsNull")); // return false; //} // 检查TestItem(测试项目)是否为空 if (!SelectData.FailureDate.HasValue) { Message.Warnning(Langs.LangGetValue("FailureDate") + Langs.LangGetValue("IsNull")); return false; } return true; } private void Initialize() { switch (StateEmun) { case OperateStateEmun.Add: Title = Langs.LangGetValue("新增"); break; case OperateStateEmun.Edit: Title = Langs.LangGetValue("修改"); break; case OperateStateEmun.Detail: break; default: break; } } } }using HandyControl.Controls; using HandyControl.Tools.Extension; using MES.Client.Models.Dtos; using MES.Client.Models.Models; using MES.Client.Tooling.Dto.MeasuringFaliureTracing; using MES.Client.Tooling.Models.MeasuringFaliureTracing; using MES.Client.Toolkit.Comm; using MES.Client.Toolkit.Enums; using MES.Client.Toolkit.HTTP; using MES.Client.UICommon.Comm; using MES.Client.UICommon.Controls; using MES.Client.UICommon.Helper; using MES.Common.Toolkit.Helper; using Microsoft.Win32; using Newtonsoft.Json; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Controls; namespace MES.Client.Tooling.UserControls { /// <summary> /// MeasuringFaliureTracing.xaml 的交互逻辑 /// </summary> public partial class MeasuringFaliureTracing : UserControl { private MeasuringFaliureTracingViewModel model; public MeasuringFaliureTracing() { InitializeComponent(); DataContext = model = new MeasuringFaliureTracingViewModel(); Loaded += MeasuringFaliureTracing_Loaded; } //} private void MeasuringFaliureTracing_Loaded(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(model.MenuID)) return; model.MenuID = string.IsNullOrEmpty(Uid) ? "" : Uid; } } public class MeasuringFaliureTracingViewModel : CommonListViewModel<MeasuringFaliureTracingInDto, MeasuringFailureTracingModel> { private MeasuringFailureTracingModel selectedModel = new(); /// <summary> /// 选中的MSA测量记录 /// </summary> public MeasuringFailureTracingModel SelectedModel { get => selectedModel; set { selectedModel = value; PCEH(); } } //private ObservableCollection<MeasuringFailureTracingModel> selectedItems = new(); //public ObservableCollection<MeasuringFailureTracingModel> SelectedItems //{ // get => selectedItems; // set // { // SetProperty(ref selectedItems, value); // SelectedIds = value.Select(item => item.Id).ToList(); // } //} //// 2. 选中的 ID 列表(传给后端) //private List<string> selectedIds = new(); //public List<string> SelectedIds //{ // get => selectedIds; // set => SetProperty(ref selectedIds, value); //} /// <summary> /// 查询条件 /// </summary> private MeasuringFaliureTracingInDto searchData = new(); public MeasuringFaliureTracingInDto SearchData { get => searchData; set { searchData = value; PCEH(); } } public MeasuringFaliureTracingViewModel() { PageIndex = 1; PageSize = 20; /// <summary> /// 查询 /// </summary> SearchCommand = new CommandBase(async l => { var loading = Dialog.Show(new UICommon.Controls.LoadingCircle(), DialogToken); try { SearchParameter = new MeasuringFaliureTracingInDto { Id = SearchData.Id, ToolCode = SearchData.ToolCode, FailureDate = SearchData.FailureDate, DeviceName = SearchData.DeviceName }; SearchParameter.PageIndex = PageIndex; SearchParameter.PageSize = PageSize; SearchParameter.StartFailureDate = SearchData.StartFailureDate; SearchParameter.EndFailureDate = SearchData.EndFailureDate; var ret = await APIHelper.PostSendDtoAsync<PaginationData>( ApiRoutes.GetMeasuringFaliureTracingList, SearchParameter ); if (ret != null) { TotalCount = ret.TotalCount; TotalPages = ret.TotalPages; var dataListJson = ret?.DataList?.ToJson() ?? "[]"; DataList = JsonConvert.DeserializeObject<ObservableCollection<MeasuringFailureTracingModel>>(dataListJson) ?? new(); if (l != null && !string.IsNullOrEmpty(l.ToString())) SelectedItem = DataList.FirstOrDefault(f => f.ToolCode == l.ToString()); } } catch (Exception ex) { Message.Error($"查询失败:{ex.Message}"); } finally { loading.Close(); } }); ModifyCommand = new CommandBase(async l => { bool flag = false; if (l != null) { flag = await Dialog.Show(new ModifyMeasuringFaliureTracing((MeasuringFailureTracingModel)l, Langs, OperateStateEmun.Edit), DialogToken).GetResultAsync<bool>(); } else { flag = await Dialog.Show(new ModifyMeasuringFaliureTracing(new MeasuringFailureTracingModel(), Langs, OperateStateEmun.Add), DialogToken).GetResultAsync<bool>(); } if (flag) { SearchCommand?.Execute(null); } }); DeleteCommand = new CommandBase(async l => { if (l is MeasuringFailureTracingModel deleteItem) { if (Message.Ask(Langs.LangGetValue("DeleteConfirm"))) { List<IdInDto> inDto = new(); inDto.Add(new IdInDto { Id = deleteItem.Id }); var ret = await APIHelper.PostSendAsync(ApiRoutes.DeleteMeasuringFaliureTracing, inDto); if (ret != null) { DataList.Remove(deleteItem); TotalCount -= 1; } } } }); ExportCommand = new CommandBase(async l => { try { var exportParam = new MeasuringFaliureTracingInDto { ToolCode = SearchData.ToolCode, DeviceName = SearchData.DeviceName, StartFailureDate = SearchData.StartFailureDate, EndFailureDate = SearchData.EndFailureDate, IsExport = true }; var exportData = await APIHelper.PostSendDtoAsync<List<MeasuringFailureTracingModel>>( ApiRoutes.ExportMeasuringFaliureTracingPageData, exportParam ); if (exportData == null || !exportData.Any()) { Message.Warnning(Langs.LangGetValue("NoDataToExport")); return; } DataTable ConvertToDataTable<T>(IEnumerable<T> dataList) { var dt = new DataTable(); if (dataList == null || !dataList.Any()) return dt; var props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var prop in props) { dt.Columns.Add(prop.Name, typeof(string)); } foreach (var item in dataList) { var row = dt.NewRow(); foreach (var prop in props) { object value = prop.GetValue(item); if (value == null) { value = string.Empty; } else if (value is DateTime date) { value = date.ToString("yyyy-MM-dd HH:mm:ss"); } else if (value is IEnumerable<string> stringList) { value = string.Join(", ", stringList); } else { value = value.ToString(); } row[prop.Name] = value; } dt.Rows.Add(row); } return dt; } var dataTable = ConvertToDataTable(exportData); bool DataTableToExcel(DataTable dt, string filePath) { try { IWorkbook workbook = filePath.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase) ? (IWorkbook)new XSSFWorkbook() : new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("ExportData"); int rowIndex = 0; var headerRow = sheet.CreateRow(rowIndex++); for (int i = 0; i < dt.Columns.Count; i++) { headerRow.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName); } foreach (DataRow dataRow in dt.Rows) { var row = sheet.CreateRow(rowIndex++); for (int i = 0; i < dt.Columns.Count; i++) { object cellValue = dataRow[i] is DBNull ? string.Empty : dataRow[i]; if (cellValue is DateTime date) { row.CreateCell(i).SetCellValue(date.ToString("yyyy-MM-dd HH:mm:ss")); } else { row.CreateCell(i).SetCellValue(cellValue?.ToString()); } } } for (int i = 0; i < dt.Columns.Count; i++) { sheet.AutoSizeColumn(i); } using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { workbook.Write(fs,false); } return true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Excel导出失败: {ex.Message}"); return false; } } var saveDialog = new SaveFileDialog { Title = Langs.LangGetValue("SelectExportPath"), Filter = "Excel文件|*.xls;*.xlsx", FileName = $"{DateTime.Now:yyyyMMdd}_MeasuringFailureExport.xlsx", RestoreDirectory = true, DefaultExt = "xlsx", OverwritePrompt = true }; if (saveDialog.ShowDialog() == true) { bool exportSuccess = DataTableToExcel(dataTable, saveDialog.FileName); if (exportSuccess) { Message.Info(Langs.LangGetValue("ExportSuccess")); } else { Message.Error(Langs.LangGetValue("ExportFailed_FileWrite")); } } } catch (Exception ex) { Message.Error($"{Langs.LangGetValue("ExportFailed")}: {ex.Message}"); } }); } public override void CommViewModelLoad() { SearchCommand?.Execute(null); } } }
08-21
import requests from bs4 import BeautifulSoup import pandas as pd import jieba import jieba.posseg as pseg import time import random import json import re from urllib.parse import quote, unquote # 配置jieba分词器 jieba.initialize() # 添加金融科技领域专有名词和公司名称 tech_keywords = ['科技', '技术', '数字', '智能', '数据', '信息', '云', 'AI', '区块链', '金融科技'] jieba.add_word('北京银行', freq=1000, tag='nt') jieba.add_word('北银', freq=1000, tag='nt') jieba.add_word('BNK', freq=1000, tag='nt') # !!!【核心修改部分】!!! 直接使用关键词构建URL模板 base_url_template = "https://www.ringdata.com/news/result?keywords={keywords}&page={page}" # 对关键词进行URL编码 encoded_keywords = quote("北京银行 科技公司 合作") # 请求头配置(替换为你的实际Cookie) headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36", "Cookie": "x-hng=lang=zh-CN&domain=www.ringdata.com; tokenWeb=eyJhbGci...", # !!!务必替换为你的有效Cookie!!! "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6", "Connection": "keep-alive", "Upgrade-Insecure-Requests": "1" } def fetch_all_news_pages(): """获取所有页面的新闻数据""" all_news = [] page = 1 max_pages = 50 # 安全限制,防止无限循环 print("开始爬取北京银行合作新闻...") while page <= max_pages: print(f"正在处理第 {page} 页。") # !!!【核心修改部分】!!! 直接拼接URL current_url = base_url_template.format(keywords=encoded_keywords, page=page) try: # 发送请求 response = requests.get( current_url, # 使用新拼接的URL headers=headers, timeout=30 ) response.raise_for_status() # 打印状态和URL用于调试(完成后可注释掉) # print(f"状态码: {response.status_code}, 请求URL: {current_url}") # 解析HTML soup = BeautifulSoup(response.text, 'html.parser') # 检查是否有结果 - 根据您提供的截图修改选择器 no_results = soup.select_one('.no-result') if no_results and "没有找到相关内容" in no_results.text: print(f"第 {page} 页无结果,停止爬取") break # !!!【关键修改】!!! 获取新闻条目 - 选择器可能需要调整 # 根据您提供的截图,新闻列表项可能是 .info-item news_items = soup.select('.info-item') # 如果上面选择器不行,可以尝试更宽泛的选择器,例如: # news_items = soup.select('.info-list li') # news_items = soup.select('.list-content > div') if not news_items: # 打印一段HTML内容来调试,帮助确定正确的选择器 print(f"第 {page} 页未找到 .info-item 元素,正在尝试确定页面结构...") # 查看页面内容的前500字符,寻找线索 # print(response.text[:500]) # 或者查找包含“北京银行”的标签 potential_items = soup.find_all(string=re.compile("北京银行")) if potential_items: print(f" 但在页面中找到了 {len(potential_items)} 处包含'北京银行'的文本。") print(f"第 {page} 页无数据,停止爬取") break print(f"发现 {len(news_items)} 条新闻") # 处理每条新闻 for item in news_items: news_data = process_news_item(item) if news_data: all_news.append(news_data) # 检查是否还有下一页(可选,更智能的停止条件) next_page = soup.select_one('.pagination .next:not(.disabled)') # 根据实际分页控件调整选择器 if not next_page: print("已是最后一页,停止爬取") break # 随机延时防止被封 sleep_time = random.uniform(2, 5) # 适当延长间隔时间 time.sleep(sleep_time) page += 1 except requests.exceptions.RequestException as e: print(f"请求第 {page} 页失败: {str(e)}") break except Exception as e: print(f"处理第 {page} 页时发生未知错误: {str(e)}") break return all_news # ... process_news_item, extract_tech_companies 等其他函数保持不变 ... def process_news_item(item): """处理单条新闻并提取合作信息""" try: # !!!【可能需要修改】!!! 根据实际HTML结构调整选择器 # 提取标题和链接 title_elem = item.select_one('a') # 尝试选择第一个a标签,或者更精确的选择器如 '.title a' if not title_elem: # 尝试其他可能的选择器 title_elem = item.select_one('.news-title, .title, .item-title') if not title_elem: print(" 无法找到标题元素,跳过此条") return None title = title_elem.get_text(strip=True) relative_url = title_elem.get('href', '') # 确保URL是完整的 if relative_url and not relative_url.startswith('http'): if relative_url.startswith('/'): full_url = f"https://www.ringdata.com{relative_url}" else: full_url = f"https://www.ringdata.com/{relative_url}" else: full_url = relative_url # 提取来源和日期 - 选择器需要根据实际页面调整 source_elem = item.select_one('.source, .news-source, .info-source') source = source_elem.get_text(strip=True) if source_elem else "未知来源" date_elem = item.select_one('.date, .news-date, .time') date = date_elem.get_text(strip=True) if date_elem else "未知日期" # 简单打印一下抓取到的信息 print(f" 抓取到: {title[:50]}... | 来源: {source} | 日期: {date}") # 获取新闻内容 content = fetch_news_content(full_url) if full_url else "" full_text = f"{title}。{content}" # 分析内容提取实体 tech_companies = extract_tech_companies(full_text) coop_companies = extract_cooperation_companies(full_text, tech_companies) # 提取合作时间 coop_date = extract_cooperation_date(content, date) # 只保留包含合作的新闻 if not coop_companies: print(f" 未在『{title[:30]}...』中识别出合作关系,跳过。") return None print(f" 分析成功: 与 {list(coop_companies)} 合作") return { "银行": "北京银行", "合作公司": list(coop_companies), "合作时间": coop_date, "新闻标题": title, "新闻发布时间": date, "新闻来源": source, "新闻链接": full_url } except Exception as e: print(f"处理新闻时出错: {str(e)}") return None # ... 其余函数 save_results, main 等保持不变 ...为什么运行不了,
09-01
针对打包后exe文件无法读取Excel的问题,怎么动态获取资源路径,请显示修改后的全部代码 import os import json import re import pandas as pd import numpy as np import win32com.client from PyQt6 import QtCore, QtGui, QtWidgets from PyQt6.QtWidgets import QFileDialog, QMessageBox class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(513, 462) self.centralwidget = QtWidgets.QWidget(parent=MainWindow) self.centralwidget.setObjectName("centralwidget") self.formLayout = QtWidgets.QFormLayout(self.centralwidget) self.formLayout.setObjectName("formLayout") # Initialize labels and line edits self.label = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label.setFont(font) self.label.setObjectName("label") self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label) self.lineEdit = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit.setObjectName("lineEdit") self.lineEdit.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(0, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit) self.label_2 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_2.setFont(font) self.label_2.setObjectName("label_2") self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_2) self.lineEdit_2 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_2.setObjectName("lineEdit_2") self.lineEdit_2.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(2, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_2) self.label_3 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_3.setFont(font) self.label_3.setObjectName("label_3") self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_3) self.lineEdit_3 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_3.setObjectName("lineEdit_3") self.lineEdit_3.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(4, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_3) self.label_4 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_4.setFont(font) self.label_4.setObjectName("label_4") self.formLayout.setWidget(6, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_4) self.lineEdit_4 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_4.setObjectName("lineEdit_4") self.lineEdit_4.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(6, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_4) self.label_5 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_5.setFont(font) self.label_5.setObjectName("label_5") self.formLayout.setWidget(8, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_5) self.lineEdit_5 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_5.setObjectName("lineEdit_5") self.lineEdit_5.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(8, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_5) self.label_6 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_6.setFont(font) self.label_6.setObjectName("label_6") self.formLayout.setWidget(10, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_6) self.lineEdit_6 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_6.setObjectName("lineEdit_6") self.lineEdit_6.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(10, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_6) self.label_7 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_7.setFont(font) self.label_7.setObjectName("label_7") self.formLayout.setWidget(12, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_7) self.lineEdit_7 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_7.setObjectName("lineEdit_7") self.lineEdit_7.setReadOnly(True) # Make it read-only to prevent manual input self.lineEdit_7.mousePressEvent = self.open_folder_dialog # Set click event self.formLayout.setWidget(12, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_7) self.label_8 = QtWidgets.QLabel(parent=self.centralwidget) font = QtGui.QFont() font.setPointSize(13) self.label_8.setFont(font) self.label_8.setObjectName("label_8") self.formLayout.setWidget(14, QtWidgets.QFormLayout.ItemRole.LabelRole, self.label_8) self.lineEdit_8 = QtWidgets.QLineEdit(parent=self.centralwidget) self.lineEdit_8.setObjectName("lineEdit_8") self.lineEdit_8.textChanged.connect(self.save_data) # Connect to save data self.formLayout.setWidget(14, QtWidgets.QFormLayout.ItemRole.FieldRole, self.lineEdit_8) self.pushButton = QtWidgets.QPushButton(parent=self.centralwidget) self.pushButton.setObjectName("pushButton") self.pushButton.setText("执行") self.pushButton.clicked.connect(self.process_data) # Connect to process data self.formLayout.setWidget(16, QtWidgets.QFormLayout.ItemRole.FieldRole, self.pushButton) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(parent=MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 513, 22)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(parent=MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) # Load previous data self.load_data() def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.label.setText(_translate("MainWindow", "付款清单开始日期")) self.label_2.setText(_translate("MainWindow", "付款清单结束日期")) self.label_3.setText(_translate("MainWindow", "ZFIR08_N")) self.label_4.setText(_translate("MainWindow", "ZFIR08_Y")) self.label_5.setText(_translate("MainWindow", "ZFIR08_D")) self.label_6.setText(_translate("MainWindow", "FBL5N_Date")) self.label_7.setText(_translate("MainWindow", "文件地址")) self.label_8.setText(_translate("MainWindow", "输入公司代码")) def open_folder_dialog(self, event): folder = QFileDialog.getExistingDirectory(None, "选择文件夹") if folder: self.lineEdit_7.setText(folder) self.save_data() # Save data when folder is selected def load_data(self): # Load the previous input data from a JSON file if os.path.exists('data.json'): with open('data.json', 'r', encoding='utf-8') as f: data = json.load(f) self.lineEdit.setText(data.get("lineEdit", "")) self.lineEdit_2.setText(data.get("lineEdit_2", "")) self.lineEdit_3.setText(data.get("lineEdit_3", "")) self.lineEdit_4.setText(data.get("lineEdit_4", "")) self.lineEdit_5.setText(data.get("lineEdit_5", "")) self.lineEdit_6.setText(data.get("lineEdit_6", "")) self.lineEdit_7.setText(data.get("lineEdit_7", "")) self.lineEdit_8.setText(data.get("lineEdit_8", "")) def save_data(self): # Save the current input data to a JSON file data = { "lineEdit": self.lineEdit.text(), "lineEdit_2": self.lineEdit_2.text(), "lineEdit_3": self.lineEdit_3.text(), "lineEdit_4": self.lineEdit_4.text(), "lineEdit_5": self.lineEdit_5.text(), "lineEdit_6": self.lineEdit_6.text(), "lineEdit_7": self.lineEdit_7.text(), "lineEdit_8": self.lineEdit_8.text(), } with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f) def process_data(self): start_date = self.lineEdit.text() end_date = self.lineEdit_2.text() ZFIR08_N = self.lineEdit_3.text() ZFIR08_Y = self.lineEdit_4.text() ZFIR08_D = self.lineEdit_5.text() FBL5N_Date = self.lineEdit_6.text() Company_Code = self.lineEdit_8.text() folder = self.lineEdit_7.text() # 定义正则表达式模式 pattern = r'^\w+_付款清单留存及检核\.xlsx$' # 获取当前目录下的所有文件 files = os.listdir('.') # 找到符合模式的文件 matching_files = [f for f in files if re.match(pattern, f)] if matching_files: # 如果找到符合条件的文件,读取第一个匹配的文件 df_FK = pd.read_excel(matching_files[0], sheet_name="代发") print(f"成功读取文件: {matching_files[0]}") # 将“过账日期”列从object类型转换为日期类型 df_FK["过账日期"] = pd.to_datetime(df_FK["过账日期"], errors='coerce') # 清洗数据,去掉过账日期为空的行 df_FK = df_FK.dropna(subset=["过账日期"]) # 格式化“过账日期”为年月日格式 df_FK["过账日期"] = df_FK["过账日期"].dt.strftime('%Y-%m-%d') # 筛选需要的字段并过滤“过账日期”在输入的日期范围内的数据 df_FK = df_FK[["公司代码", "凭证编号", "分配", "金额", "客户编码", "过账日期"]] df_FK = df_FK.query("@start_date <= 过账日期 <= @end_date") # # 导出txt - 修改为使用folder路径 # df_FK[["凭证编号"]].to_csv("./重复检核结果凭证编号.txt", index=False, sep='\t', encoding='utf-8') df_FK[["凭证编号"]].to_csv(f"{folder}/重复检核结果凭证编号.txt", index=False, sep='\t', encoding='utf-8') print("重复检核结果凭证编号已保存为 '重复检核结果凭证编号.TXT'") # SAP下载 SapGuiAuto_1 = win32com.client.GetObject("SAPGUI") application_1 = SapGuiAuto_1.GetScriptingEngine connections_1 = application_1.Children session = connections_1[0].Children(0) session.findById("wnd[0]").maximize() session.findById("wnd[0]/tbar[0]/okcd").text = "ZFIR08" session.findById("wnd[0]").sendVKey(0) session.findById("wnd[0]/usr/ctxtP_BUKRS").text = Company_Code session.findById("wnd[0]/usr/txtS_GJAHR-LOW").text = ZFIR08_N session.findById("wnd[0]/usr/txtS_MONAT1-LOW").text = ZFIR08_Y session.findById("wnd[0]/usr/txtS_MONAT1-HIGH").text = ZFIR08_D session.findById("wnd[0]/usr/txtS_MONAT1-HIGH").setFocus() session.findById("wnd[0]/usr/txtS_MONAT1-HIGH").caretPosition = 0 session.findById("wnd[0]/usr/btn%_S_BELNR_%_APP_%-VALU_PUSH").press() session.findById("wnd[1]/tbar[0]/btn[23]").press() session.findById("wnd[2]/usr/ctxtDY_PATH").text = folder session.findById("wnd[2]/usr/ctxtDY_FILENAME").text = "重复检核结果凭证编号.TXT" session.findById("wnd[2]/usr/ctxtDY_FILENAME").caretPosition = 34 session.findById("wnd[2]/tbar[0]/btn[0]").press() session.findById("wnd[1]/tbar[0]/btn[8]").press() session.findById("wnd[0]/tbar[1]/btn[8]").press() session.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").select() session.findById("wnd[1]/tbar[0]/btn[0]").press() session.findById("wnd[1]/usr/ctxtDY_PATH").text = folder session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = f"{Company_Code}ZFIR08.XLSX" session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 24 session.findById("wnd[1]/tbar[0]/btn[0]").press() # 创建Excel应用程序对象 excel = win32com.client.Dispatch("Excel.Application") excel.Visible = False # 设置Excel应用为不可见 # 关闭所有打开的Excel工作簿 workbooks = excel.Workbooks for wb in workbooks: try: wb.Close(SaveChanges=False) # 关闭工作簿,不保存更改 except Exception as e: print(f"关闭工作簿时出错: {e}") # 退出Excel应用程序 excel.Quit() session.findById("wnd[0]/tbar[0]/btn[3]").press() print(f"{Company_Code}ZFIR08已经下载完") # FBL5N session.findById("wnd[0]/tbar[0]/btn[15]").press() SapGuiAuto_1 = win32com.client.GetObject("SAPGUI") application_1 = SapGuiAuto_1.GetScriptingEngine connections_1 = application_1.Children session = connections_1[0].Children(0) session.findById("wnd[0]").maximize() session.findById("wnd[0]/tbar[0]/okcd").text = "FBL5N" session.findById("wnd[0]").sendVKey(0) session.findById("wnd[0]/tbar[1]/btn[17]").press() session.findById("wnd[1]/usr/txtENAME-LOW").text = "" session.findById("wnd[1]/usr/txtENAME-LOW").setFocus() session.findById("wnd[1]/usr/txtENAME-LOW").caretPosition = 0 session.findById("wnd[1]/tbar[0]/btn[8]").press() QtCore.QThread.sleep(1) # Sleep for a moment to allow loading session.findById("wnd[1]/usr/cntlALV_CONTAINER_1/shellcont/shell").setCurrentCell(58, "TEXT") session.findById("wnd[1]/usr/cntlALV_CONTAINER_1/shellcont/shell").firstVisibleRow = 45 session.findById("wnd[1]/usr/cntlALV_CONTAINER_1/shellcont/shell").selectedRows = "58" session.findById("wnd[1]/tbar[0]/btn[2]").press() session.findById("wnd[0]/usr/ctxtDD_BUKRS-LOW").text = Company_Code session.findById("wnd[0]/usr/ctxtPA_STIDA").text = FBL5N_Date session.findById("wnd[0]/usr/ctxtPA_STIDA").setFocus() session.findById("wnd[0]/usr/ctxtPA_STIDA").caretPosition = 10 session.findById("wnd[0]/tbar[1]/btn[8]").press() session.findById("wnd[0]/mbar/menu[0]/menu[3]/menu[1]").select() session.findById("wnd[1]/tbar[0]/btn[0]").press() session.findById("wnd[1]/usr/ctxtDY_PATH").text = folder session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = f"{Company_Code}FBL5N.XLSX" session.findById("wnd[1]/usr/ctxtDY_FILENAME").caretPosition = 2 session.findById("wnd[1]/tbar[0]/btn[0]").press() # 创建Excel应用程序对象 excel = win32com.client.Dispatch("Excel.Application") excel.Visible = False # 设置Excel应用为不可见 # 关闭所有打开的Excel工作簿 workbooks = excel.Workbooks for wb in workbooks: try: wb.Close(SaveChanges=False) # 关闭工作簿,不保存更改 except Exception as e: print(f"关闭工作簿时出错: {e}") # 退出Excel应用程序 excel.Quit() session.findById("wnd[0]/tbar[0]/btn[3]").press() print(f"{Company_Code}FBL5N已经下载完") session.findById("wnd[0]/tbar[0]/btn[15]").press() # 验证文本和行数第一个条件正确 ZFIR08 df_FK["辅助数据"] = df_FK["公司代码"].astype(str) + "_" + df_FK["金额"].astype(str) + "_" + df_FK["客户编码"].astype(str) # # 新增“重复检核结果”列,标识辅助数据中的重复项 df_FK["辅助数据重复检核结果"] = df_FK.duplicated(subset=["辅助数据"], keep=False).replace({True: '重复', False: '唯一'}) # # 验证文凭证编号第二个条件正确 df_ZFIR08 = pd.read_excel(f"./{Company_Code}FIR08.XLSX") df_ZFIR08.rename(columns={'凭证编码': '凭证编号'}, inplace=True) df_ZFIR08['行项目文本'] = df_ZFIR08.groupby('凭证编号')['行项目文本'].ffill() df_ZFIR08['凭证编号'] = df_ZFIR08['凭证编号'].astype(str).str.lstrip('0') df_FK['凭证编号'] = df_FK['凭证编号'].astype(str).str.lstrip('0') df_ZFIR08_凭证编号14 = df_ZFIR08[df_ZFIR08['凭证编号'].str.startswith('14')] df_ZFIR08 = df_ZFIR08[df_ZFIR08["借贷标识"] == "S"] df_ZFIR08 = df_ZFIR08.drop_duplicates(subset=["凭证编号"], keep='last') # 6. 合并两个 DataFrame(14 开头的凭证 + 借贷标识为 "S" 的去重数据) df_combined = pd.concat([df_ZFIR08_凭证编号14, df_ZFIR08], ignore_index=True) df_combined = pd.merge(df_FK, df_combined[["凭证编号", "行项目文本"]], on='凭证编号', how='left') df_combined["重复检核结果"] = df_combined.duplicated(subset=["行项目文本"], keep=False).replace({True: '重复', False: '唯一'}) # FBL5N df_FBL5N = pd.read_excel(f"./{Company_Code}FBL5N.XLSX") df_FBL5N.rename(columns={'客户': '客户编码'}, inplace=True) df_FBL5N = df_FBL5N.drop_duplicates(subset=["客户编码"], keep='last') df_FBL5N['客户编码'] = df_FBL5N['客户编码'].astype(str) # 合并数据 df_FK_5N = pd.merge(df_combined,df_FBL5N[["客户编码", "文本"]], on='客户编码', how='left') # 更推荐使用NumPy的where函数代替apply,效率更高: df_FK_5N['FBL5N数据检验'] = np.where(df_FK_5N['行项目文本'].astype(str) == df_FK_5N['文本'].astype(str), '重复', '唯一') with pd.ExcelWriter(os.path.join(folder, "付款排查检核记录.xlsx")) as writer: df_greater_than_10000 = df_FK[df_FK['金额'] > 10000] df_greater_than_10000.to_excel(writer, index=False, sheet_name='大于10000') df_combined.to_excel(writer, index=False,sheet_name='ZFIR08付款排查表重复和唯一结果') df_FK_5N.to_excel(writer, index=False,sheet_name='FBL5N重复检核结果') # 保存全部检核结果 print("数据已保存为 '付款排查重复检核结果.xlsx'") # 显示完成提示 self.show_message("处理完成", "数据处理已完成,结果已保存。") def show_message(self, title, message): msg_box = QMessageBox() msg_box.setWindowTitle(title) msg_box.setText(message) msg_box.exec() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec())
06-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值