0%

1.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
import tkinter as tk
from tkinter import messagebox, ttk
import json
import random
import os

class VocabularyApp:
def __init__(self, root):
self.root = root
self.root.title("背单词软件")
self.root.geometry("500x800") # 调整窗口大小

# 设置主题颜色
self.bg_color = "#f0f0f0"
self.button_color = "#4a90e2"
self.button_text_color = "white"
self.frame_bg = "#ffffff"

self.root.configure(bg=self.bg_color)

# 加载单词数据
self.words = self.load_words()
self.current_word = None
self.practice_mode = False
self.exam_mode = False
self.exam_words = []
self.current_exam_index = 0
self.correct_count = 0
self.user_answers = [] # 存储用户的答案
self.answer_shown = False # 标记答案是否已显示
self.last_word = None # 存储上一题的单词

# 创建界面元素
self.create_widgets()

# 显示第一个单词
self.show_next_word()

# 绑定按键
self.root.bind('<Up>', self.handle_show_answer) # 上键显示答案
self.root.bind('<Right>', self.handle_next) # 右键下一题
self.root.bind('<Return>', self.handle_next) # 回车键也支持下一题

def handle_show_answer(self, event):
if self.practice_mode and not self.exam_mode: # 只在练习模式下显示答案
self.show_current_answer()

def handle_next(self, event):
if self.practice_mode or self.exam_mode:
self.check_answer()
else:
self.show_next_word()

def show_current_answer(self):
if not self.current_word:
return

if not self.answer_shown:
self.word_label.config(text=self.current_word["word"])
self.example_label.config(text=self.current_word["example"])
self.answer_shown = True
else:
self.word_label.config(text="")
self.example_label.config(text="")
self.answer_shown = False

def load_words(self):
# 如果words.json不存在,创建示例数据
if not os.path.exists('words.json'):
sample_words = [
{"word": "apple", "meaning": "苹果", "example": "I eat an apple every day."},
{"word": "book", "meaning": "书", "example": "I love reading books."},
{"word": "computer", "meaning": "电脑", "example": "I work on my computer."}
]
with open('words.json', 'w', encoding='utf-8') as f:
json.dump(sample_words, f, ensure_ascii=False, indent=2)

# 加载单词数据
with open('words.json', 'r', encoding='utf-8') as f:
return json.load(f)

def save_words(self):
with open('words.json', 'w', encoding='utf-8') as f:
json.dump(self.words, f, ensure_ascii=False, indent=2)

def create_widgets(self):
# 创建主框架
main_frame = tk.Frame(self.root, bg=self.bg_color)
main_frame.pack(expand=True, fill='both', padx=20, pady=20)

# 标题
title_label = tk.Label(main_frame, text="单词学习助手", font=("微软雅黑", 24, "bold"), bg=self.bg_color)
title_label.pack(pady=(0, 20))

# 搜索框架
search_frame = tk.Frame(main_frame, bg=self.frame_bg, padx=10, pady=10)
search_frame.pack(fill='x', pady=(0, 20))

self.search_entry = tk.Entry(search_frame, font=("微软雅黑", 12))
self.search_entry.pack(side=tk.LEFT, padx=5, expand=True, fill='x')

search_button = tk.Button(search_frame, text="搜索", command=self.search_word,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 10), padx=15)
search_button.pack(side=tk.LEFT, padx=5)

# 模式选择按钮框架
mode_frame = tk.Frame(main_frame, bg=self.bg_color)
mode_frame.pack(pady=10)

# 练习模式按钮
self.practice_button = tk.Button(mode_frame, text="开始练习", command=self.toggle_practice_mode,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
self.practice_button.pack(side=tk.LEFT, padx=5)

# 考试模式按钮
self.exam_button = tk.Button(mode_frame, text="开始考试", command=self.start_exam,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
self.exam_button.pack(side=tk.LEFT, padx=5)

# 练习模式输入框(初始隐藏)
self.practice_frame = tk.Frame(main_frame, bg=self.frame_bg, padx=10, pady=10)
self.practice_frame.pack(fill='x', pady=10)

self.answer_entry = tk.Entry(self.practice_frame, font=("微软雅黑", 12))
self.answer_entry.pack(side=tk.LEFT, padx=5, expand=True, fill='x')

self.check_button = tk.Button(self.practice_frame, text="显示答案", command=self.check_answer,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 10), padx=15)
self.check_button.pack(side=tk.LEFT, padx=5)

# 添加提示标签
self.hint_label = tk.Label(self.practice_frame, text="按右键或回车进入下一题,按上键显示答案",
font=("微软雅黑", 10), bg=self.frame_bg, fg="#666666")
self.hint_label.pack(side=tk.LEFT, padx=5)

# 添加上一题显示区域
self.last_word_frame = tk.Frame(main_frame, bg=self.frame_bg, padx=20, pady=20)
self.last_word_frame.pack(fill='x', pady=10)

self.last_word_label = tk.Label(self.last_word_frame, text="上一题:", font=("微软雅黑", 12, "bold"), bg=self.frame_bg)
self.last_word_label.pack(anchor='w', pady=5)

self.last_word_text = tk.Label(self.last_word_frame, text="", font=("微软雅黑", 12), bg=self.frame_bg)
self.last_word_text.pack(anchor='w', pady=5)

self.last_example_text = tk.Label(self.last_word_frame, text="", font=("微软雅黑", 10), bg=self.frame_bg,
wraplength=400, justify='left')
self.last_example_text.pack(anchor='w', pady=5)

# 隐藏练习模式相关控件
self.practice_frame.pack_forget()

# 单词显示区域
word_frame = tk.Frame(main_frame, bg=self.frame_bg, padx=20, pady=20)
word_frame.pack(fill='x', pady=10)

self.word_label = tk.Label(word_frame, text="", font=("微软雅黑", 24, "bold"), bg=self.frame_bg)
self.word_label.pack(pady=10)

self.meaning_label = tk.Label(word_frame, text="", font=("微软雅黑", 18), bg=self.frame_bg)
self.meaning_label.pack(pady=10)

self.example_label = tk.Label(word_frame, text="", font=("微软雅黑", 12), bg=self.frame_bg,
wraplength=400, justify='left')
self.example_label.pack(pady=10)

# 按钮框架
button_frame = tk.Frame(main_frame, bg=self.bg_color)
button_frame.pack(pady=20)

# 创建按钮样式
button_style = {
'bg': self.button_color,
'fg': self.button_text_color,
'font': ("微软雅黑", 10),
'padx': 15,
'pady': 5
}

self.show_button = tk.Button(button_frame, text="显示答案", command=self.show_answer, **button_style)
self.show_button.pack(side=tk.LEFT, padx=5)

self.next_button = tk.Button(button_frame, text="下一个", command=self.show_next_word, **button_style)
self.next_button.pack(side=tk.LEFT, padx=5)

self.edit_button = tk.Button(button_frame, text="编辑", command=self.edit_word, **button_style)
self.edit_button.pack(side=tk.LEFT, padx=5)

self.delete_button = tk.Button(button_frame, text="删除", command=self.delete_word, **button_style)
self.delete_button.pack(side=tk.LEFT, padx=5)

# 添加新单词的按钮
self.add_button = tk.Button(main_frame, text="添加新单词", command=self.show_add_word_window,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
self.add_button.pack(pady=10)

def toggle_practice_mode(self):
if self.exam_mode:
self.exam_mode = False
self.exam_button.config(text="开始考试")
self.practice_frame.pack_forget()
self.show_next_word()
return

self.practice_mode = not self.practice_mode
if self.practice_mode:
self.practice_button.config(text="退出练习")
self.practice_frame.pack(fill='x', pady=10)
self.word_label.pack_forget()
self.show_button.pack_forget()
self.show_next_word()
else:
self.practice_button.config(text="开始练习")
self.practice_frame.pack_forget()
self.word_label.pack(pady=20)
self.show_button.pack(in_=self.show_button.master, side=tk.LEFT, padx=5)
self.show_next_word()

def show_next_word(self):
if self.words:
# 保存当前单词作为上一题
if self.current_word:
self.last_word = self.current_word
# 更新上一题显示
self.last_word_text.config(text=f"{self.last_word['word']} - {self.last_word['meaning']}")
self.last_example_text.config(text=self.last_word['example'])

self.current_word = random.choice(self.words)
if self.practice_mode:
self.meaning_label.config(text=self.current_word["meaning"])
self.example_label.config(text="")
self.answer_entry.delete(0, tk.END)
else:
self.word_label.config(text=self.current_word["word"])
self.meaning_label.config(text="")
self.example_label.config(text="")

def show_answer(self):
if self.current_word:
self.meaning_label.config(text=self.current_word["meaning"])
self.example_label.config(text=self.current_word["example"])

def search_word(self):
search_text = self.search_entry.get().strip().lower()
if not search_text:
messagebox.showwarning("警告", "请输入要搜索的单词!")
return

found_words = [word for word in self.words if search_text in word["word"].lower()]
if not found_words:
messagebox.showinfo("搜索结果", "未找到匹配的单词!")
return

# 创建搜索结果窗口
search_window = tk.Toplevel(self.root)
search_window.title("搜索结果")
search_window.geometry("300x400")

# 创建列表框
listbox = tk.Listbox(search_window, width=40, height=15)
listbox.pack(pady=10)

# 添加搜索结果
for word in found_words:
listbox.insert(tk.END, f"{word['word']} - {word['meaning']}")

def show_selected_word():
selection = listbox.curselection()
if selection:
selected_word = found_words[selection[0]]
self.current_word = selected_word
self.word_label.config(text=selected_word["word"])
self.meaning_label.config(text=selected_word["meaning"])
self.example_label.config(text=selected_word["example"])
search_window.destroy()

# 添加选择按钮
select_button = tk.Button(search_window, text="选择", command=show_selected_word)
select_button.pack(pady=10)

def edit_word(self):
if not self.current_word:
messagebox.showwarning("警告", "请先选择一个单词!")
return

# 创建编辑窗口
edit_window = tk.Toplevel(self.root)
edit_window.title("编辑单词")
edit_window.geometry("300x200")

# 创建输入框
tk.Label(edit_window, text="单词:").pack()
word_entry = tk.Entry(edit_window)
word_entry.insert(0, self.current_word["word"])
word_entry.pack()

tk.Label(edit_window, text="意思:").pack()
meaning_entry = tk.Entry(edit_window)
meaning_entry.insert(0, self.current_word["meaning"])
meaning_entry.pack()

tk.Label(edit_window, text="例句:").pack()
example_entry = tk.Entry(edit_window)
example_entry.insert(0, self.current_word["example"])
example_entry.pack()

def save_edit():
# 更新单词信息
self.current_word["word"] = word_entry.get()
self.current_word["meaning"] = meaning_entry.get()
self.current_word["example"] = example_entry.get()

# 保存到文件
self.save_words()

# 更新显示
self.word_label.config(text=self.current_word["word"])
self.meaning_label.config(text=self.current_word["meaning"])
self.example_label.config(text=self.current_word["example"])

messagebox.showinfo("成功", "单词修改成功!")
edit_window.destroy()

# 保存按钮
save_button = tk.Button(edit_window, text="保存", command=save_edit)
save_button.pack(pady=10)

def delete_word(self):
if not self.current_word:
messagebox.showwarning("警告", "请先选择一个单词!")
return

if messagebox.askyesno("确认", f"确定要删除单词 '{self.current_word['word']}' 吗?"):
self.words.remove(self.current_word)
self.save_words()
self.show_next_word()
messagebox.showinfo("成功", "单词删除成功!")

def show_add_word_window(self):
# 创建新窗口
add_window = tk.Toplevel(self.root)
add_window.title("添加新单词")
add_window.geometry("400x400")
add_window.configure(bg=self.bg_color)

# 创建输入框架
input_frame = tk.Frame(add_window, bg=self.frame_bg, padx=20, pady=20)
input_frame.pack(expand=True, fill='both', padx=20, pady=20)

# 创建输入框
tk.Label(input_frame, text="单词:", font=("微软雅黑", 12), bg=self.frame_bg).pack(pady=(0, 5))
word_entry = tk.Entry(input_frame, font=("微软雅黑", 12))
word_entry.pack(fill='x', pady=(0, 10))

tk.Label(input_frame, text="意思:", font=("微软雅黑", 12), bg=self.frame_bg).pack(pady=(0, 5))
meaning_entry = tk.Entry(input_frame, font=("微软雅黑", 12))
meaning_entry.pack(fill='x', pady=(0, 10))

tk.Label(input_frame, text="例句:", font=("微软雅黑", 12), bg=self.frame_bg).pack(pady=(0, 5))
example_entry = tk.Entry(input_frame, font=("微软雅黑", 12))
example_entry.pack(fill='x', pady=(0, 10))

def save_word():
new_word = {
"word": word_entry.get(),
"meaning": meaning_entry.get(),
"example": example_entry.get()
}
self.words.append(new_word)
self.save_words()
messagebox.showinfo("成功", "单词添加成功!")
add_window.destroy()

# 保存按钮
save_button = tk.Button(input_frame, text="保存", command=save_word,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
save_button.pack(pady=10)

def check_answer(self):
if not self.current_word:
return

user_answer = self.answer_entry.get().strip().lower()
correct_answer = self.current_word["word"].lower()

if self.exam_mode:
# 保存用户答案
self.user_answers.append({
"word": self.current_word["word"],
"meaning": self.current_word["meaning"],
"user_answer": user_answer,
"is_correct": user_answer == correct_answer
})

if user_answer == correct_answer:
self.correct_count += 1

self.current_exam_index += 1
self.show_exam_word()
else:
if user_answer == correct_answer:
messagebox.showinfo("正确", "回答正确!")
else:
messagebox.showinfo("错误", f"回答错误!正确答案是:{self.current_word['word']}")
self.example_label.config(text=self.current_word["example"])
self.show_next_word() # 自动进入下一题

def start_exam(self):
if len(self.words) < 5:
messagebox.showwarning("警告", "单词库中单词数量不足,请先添加更多单词!")
return

# 创建考试设置窗口
exam_window = tk.Toplevel(self.root)
exam_window.title("考试设置")
exam_window.geometry("300x300")
exam_window.configure(bg=self.bg_color)

# 创建输入框架
input_frame = tk.Frame(exam_window, bg=self.frame_bg, padx=20, pady=20)
input_frame.pack(expand=True, fill='both', padx=20, pady=20)

# 题目数量选择
tk.Label(input_frame, text="选择题目数量:", font=("微软雅黑", 12), bg=self.frame_bg).pack(pady=(0, 10))

num_frame = tk.Frame(input_frame, bg=self.frame_bg)
num_frame.pack(pady=10)

num_var = tk.StringVar(value="10")
for num in ["5", "10", "15", "20"]:
tk.Radiobutton(num_frame, text=num, variable=num_var, value=num,
font=("微软雅黑", 12), bg=self.frame_bg).pack(side=tk.LEFT, padx=10)

def start_exam_with_num():
num = int(num_var.get())
if num > len(self.words):
messagebox.showwarning("警告", f"单词库中只有{len(self.words)}个单词,请选择更少的题目数量!")
return

self.exam_mode = True
self.practice_mode = False
self.exam_words = random.sample(self.words, num)
self.current_exam_index = 0
self.correct_count = 0

# 更新界面
self.practice_button.config(text="开始练习")
self.exam_button.config(text="退出考试")
self.practice_frame.pack_forget()
self.word_label.pack(pady=10)
self.show_button.pack(in_=self.show_button.master, side=tk.LEFT, padx=5)

# 显示第一题
self.show_exam_word()
exam_window.destroy()

# 开始考试按钮
start_button = tk.Button(input_frame, text="开始考试", command=start_exam_with_num,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
start_button.pack(pady=10)

def show_exam_word(self):
if self.current_exam_index < len(self.exam_words):
self.current_word = self.exam_words[self.current_exam_index]
self.word_label.config(text=f"第 {self.current_exam_index + 1} 题")
self.meaning_label.config(text=self.current_word["meaning"])
self.example_label.config(text="")
self.answer_entry.delete(0, tk.END)
self.practice_frame.pack(fill='x', pady=10)
self.answer_entry.focus() # 自动聚焦到输入框
self.answer_shown = False # 重置答案显示状态
else:
self.show_exam_result()

def show_exam_result(self):
score = int(self.correct_count / len(self.exam_words) * 100)

# 创建结果窗口
result_window = tk.Toplevel(self.root)
result_window.title("考试结果")
result_window.geometry("700x600")
result_window.configure(bg=self.bg_color)

# 显示结果
result_frame = tk.Frame(result_window, bg=self.frame_bg, padx=20, pady=20)
result_frame.pack(expand=True, fill='both', padx=20, pady=20)

# 显示总分
score_text = f"考试结束!\n\n总分:{score}分\n答对题目:{self.correct_count}/{len(self.exam_words)}"
tk.Label(result_frame, text=score_text, font=("微软雅黑", 16, "bold"),
bg=self.frame_bg, justify='center').pack(pady=10)

# 创建详细答案列表
answer_frame = tk.Frame(result_frame, bg=self.frame_bg)
answer_frame.pack(fill='both', expand=True, pady=10)

# 添加表头
headers = ["题目", "中文", "你的答案", "正确答案", "结果"]
for i, header in enumerate(headers):
tk.Label(answer_frame, text=header, font=("微软雅黑", 12, "bold"),
bg=self.frame_bg, width=10).grid(row=0, column=i, padx=5, pady=5)

# 添加每道题的详细答案
for i, answer in enumerate(self.user_answers, 1):
# 题目序号
tk.Label(answer_frame, text=str(i), font=("微软雅黑", 10),
bg=self.frame_bg).grid(row=i, column=0, padx=5, pady=2)

# 中文意思
tk.Label(answer_frame, text=answer["meaning"], font=("微软雅黑", 10),
bg=self.frame_bg).grid(row=i, column=1, padx=5, pady=2)

# 用户答案
tk.Label(answer_frame, text=answer["user_answer"], font=("微软雅黑", 10),
bg=self.frame_bg).grid(row=i, column=2, padx=5, pady=2)

# 正确答案
tk.Label(answer_frame, text=answer["word"], font=("微软雅黑", 10),
bg=self.frame_bg).grid(row=i, column=3, padx=5, pady=2)

# 结果(对/错)
result_text = "✓" if answer["is_correct"] else "✗"
result_color = "#4CAF50" if answer["is_correct"] else "#F44336"
tk.Label(answer_frame, text=result_text, font=("微软雅黑", 12, "bold"),
fg=result_color, bg=self.frame_bg).grid(row=i, column=4, padx=5, pady=2)

# 关闭按钮
close_button = tk.Button(result_frame, text="关闭", command=result_window.destroy,
bg=self.button_color, fg=self.button_text_color,
font=("微软雅黑", 12), padx=20, pady=5)
close_button.pack(pady=10)

# 重置考试状态
self.exam_mode = False
self.exam_button.config(text="开始考试")
self.practice_frame.pack_forget()
self.user_answers = [] # 清空答案记录
self.show_next_word()

if __name__ == "__main__":
root = tk.Tk()
app = VocabularyApp(root)
root.mainloop()

2.图片演示

单词文件存在同级目录下的words里

3.软件下载

单词小助手下载

1.创建虚拟环境

1
python -m venv venv

点击

如果像创建多个虚拟环境,只需更改名称

1
python -m venv venv2

2.激活虚拟环境

windows

1
.\venv\Scripts\activate

3.安装python包

1
pip install pyinstaller

写一个程序进行打包

1
2
3
print("Hello, world!")
# 没有input,输出Hello, world!程序会直接退出
input("按回车键退出...")

打包命令

1
pyinstaller --onefile --noconsole .\hello.py 

生成的exe文件在dist目录下

定义一个函数quadratic(a, b, c),接收3个参数,返回一元二次方程 axx+bx+c=0 的两个解。

求解公式为:

**注意:**a!=0 ,bb-4ac>=0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# quadratic_solver.py

def quadratic(a, b, c):
if a == 0:
return "错误: a不能为0"
n = b**2 - 4*a*c
if n < 0:
return "方程无解"
x1 = (-b + n**0.5) / (2*a) # 使用 n 的平方根
x2 = (-b - n**0.5) / (2*a) # 使用 n 的平方根
if x1 == x2:
return x1
return x1, x2

while True:
try:
# 允许用户输入参数
a = float(input("请输入 a: "))
b = float(input("请输入 b: "))
c = float(input("请输入 c: "))
result = quadratic(a, b, c)
print(result)
except ValueError:
print("输入无效,请输入数字。")

求解小程序

效果图

1.依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.25</version>
</dependency>

<!--excel工具 -->
<dependency>
<groupId>cn.idev.excel</groupId>
<artifactId>fastexcel</artifactId>
<version>1.0.0</version>
</dependency>


<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>

2.实体类

以 @ExcelProperty({“每日质量报警统计信息”,”站别”})为例

“每日质量报警统计信息”代表标题;”站别”代表表头

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import cn.idev.excel.annotation.ExcelProperty;
import cn.idev.excel.annotation.write.style.ColumnWidth;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@ColumnWidth(26) // 默认列宽
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
public class QualityAlarmExcelDTO {
@ExcelProperty({"每日质量报警统计信息","站别"})
private String deviceName ;
@ExcelProperty({"每日质量报警统计信息","抽样总数"})
private String all ;
@ExcelProperty({"每日质量报警统计信息","超时未测量"})
private String timeOut ;
@ExcelProperty({"每日质量报警统计信息","占比"})
private String timeOutRatio ;

@ExcelProperty({"每日质量报警统计信息","数据超差"})
private String dataOut;
@ExcelProperty({"每日质量报警统计信息","占比"})
private String dataOutRatio;
@ExcelProperty({"每日质量报警统计信息","总异常比例"})
private String allRatio;

}

3.方法

此处使用的是若以框架,定时任务为每日凌晨发送(0 0 0 * * ?)

alarmInfoService获取前一天的数据信息

deviceWorkStationService查询设备

两者之间通过id关联

qualitySummaryExcelDay()方法中

qualitySummaryExcelDay()方法为固定格式

其中 String fileName = “C:/export/工作站检测质量报警_”+ DateUtil.formatDate(DateUtil.yesterday()) + “.xlsx”;是文件路径以及文件名设置

FastExcel.write(fileName, QualityAlarmExcelDTO.class)
.registerWriteHandler(horizontalCellStyleStrategy)
.sheet(“质量报警”).doWrite(qualityInfo);

文件名,引用实体类,表格样式,工作表(见下图),具体的数据

getQualityInfo()方法中

用hash存入两种报警信息的id,以及报警次数

检索前一天的报警信息根据具体的sql来调整

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package com.caya.quartz.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.metadata.style.WriteCellStyle;
import cn.idev.excel.write.style.HorizontalCellStyleStrategy;
import com.caya.manager.domain.DeviceWorkStation;
import com.caya.manager.domain.VO.AlarmInfoVO;
import com.caya.manager.domain.dto.QualityAlarmExcelDTO;
import com.caya.manager.service.IAlarmInfoService;
import com.caya.manager.service.IDeviceWorkStationService;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

@Component("qualityAlarmExcelTask")
public class QualityAlarmExcelTask {


@Autowired
private IAlarmInfoService alarmInfoService;


@Autowired
private IDeviceWorkStationService deviceWorkStationService;
private static final int ALARM_TYPE_TIMEOUT = 147;
private static final int ALARM_TYPE_DATA_OUT = 148;


public void qualitySummaryExcelDay(){

List<QualityAlarmExcelDTO> qualityInfo = getQualityInfo();


String fileName = "C:/export/工作站检测质量报警_"+ DateUtil.formatDate(DateUtil.yesterday()) + ".xlsx";
File file = new File(fileName);
if (!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//设置头居中
headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//设置内容
WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//设置 水平居中
contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
//内容策略
HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

FastExcel.write(fileName, QualityAlarmExcelDTO.class)
.registerWriteHandler(horizontalCellStyleStrategy)
.sheet("质量报警").doWrite(qualityInfo);

}

public List<QualityAlarmExcelDTO> getQualityInfo(){
//查询所有类型的工作站
List<DeviceWorkStation> deviceWorkStations = deviceWorkStationService.selectDeviceWorkStationList(new DeviceWorkStation());


//超时未测量统计
HashMap<Long,Float> timeOutNum=new HashMap<>();
for (DeviceWorkStation deviceWorkStation:deviceWorkStations ) {
timeOutNum.put(deviceWorkStation.getId(), (float) 0);
}
//数据超差统计
HashMap<Long,Float> dataOutNum=new HashMap<>();
for (DeviceWorkStation deviceWorkStation:deviceWorkStations ) {
dataOutNum.put(deviceWorkStation.getId(), (float) 0);
}


//检索前一天的报警信息
DateTime yesterday = DateUtil.yesterday();
String beginOfDay = DateUtil.beginOfDay(yesterday).toString("yyyy-MM-dd HH:mm:ss");
String endOfDay = DateUtil.endOfDay(yesterday).toString("yyyy-MM-dd HH:mm:ss");
AlarmInfoVO alarmInfoVO = new AlarmInfoVO();
Map<String,Object> params=new HashMap<>();
params.put("beginTime",beginOfDay);
params.put("endTime",endOfDay);
alarmInfoVO.setParams(params);
List<AlarmInfoVO> alarmInfoVOS = alarmInfoService.selectAlarmInfoList(alarmInfoVO);

//查询报警类型
// Object redisData = redisCache.getCacheObject("sys_dict:alarm_type_info");
// List<SysDictData> cacheList = JSON.parseArray(redisData.toString(), SysDictData.class);
// for (SysDictData sysDictData:cacheList) {
// //查询编号
// sysDictData.getDictCode();
//此处编号147:超时未测量; 148:数据超差
// }

String deviceName="";
String all="";
String timeOut="";
String timeOutRatio="";
String dataOut="";
String dataOutRatio="";
String allRatio="";

//超时未测量总数
float timeOutAll=0;
//数据采集异常报警数
float dataOutAll=0;

List<QualityAlarmExcelDTO> qualityAlarmExcel=new ArrayList<>();

//遍历报警
for (AlarmInfoVO alarm:alarmInfoVOS) {
//查询报警类型为147的报警
if (alarm.getTypeSysDictDataId()==ALARM_TYPE_TIMEOUT){
//匹配报警的id
for (Long deviceId :timeOutNum.keySet()) {
//id相同,报警类型相同,对应的报警数量+1
if (Objects.equals(deviceId, alarm.getDeviceWorkStationId())){
float timeOutAlarm = timeOutNum.get(deviceId);
timeOutNum.put(deviceId,timeOutAlarm+1);
}
}
//超时未测量+1
timeOutAll++;
}
//查询报警类型为148的报警
if (alarm.getTypeSysDictDataId()==ALARM_TYPE_DATA_OUT){
//匹配报警的id
for (Long deviceId :dataOutNum.keySet()) {
//id相同,报警类型相同,对应的报警数量+1
if (Objects.equals(deviceId, alarm.getDeviceWorkStationId())){
float dataOutAlarm = dataOutNum.get(deviceId);
dataOutNum.put(deviceId,dataOutAlarm+1);
}
}
//超时未测量+1
dataOutAll++;
}
}

for (DeviceWorkStation deviceWorkStation: deviceWorkStations) {
deviceName=deviceWorkStation.getName();
Float aFloat = timeOutNum.get(deviceWorkStation.getId());
Float bFloat = dataOutNum.get(deviceWorkStation.getId());
all= String.valueOf(aFloat.intValue() + bFloat.intValue());
timeOut= String.valueOf(aFloat.intValue());
timeOutRatio = timeOutAll == 0 ? "0%" : (aFloat / timeOutAll * 100) + "%";
dataOut=String.valueOf(bFloat.intValue());
dataOutRatio = dataOutAll == 0 ? "0%" : (bFloat / dataOutAll * 100) + "%";
allRatio = (timeOutAll + dataOutAll) == 0 ? "0%" : ((aFloat + bFloat) / (timeOutAll + dataOutAll) * 100) + "%";
QualityAlarmExcelDTO qualityAlarmExcelDTO=new QualityAlarmExcelDTO(deviceName,all,timeOut,timeOutRatio,dataOut,dataOutRatio,allRatio);
qualityAlarmExcel.add(qualityAlarmExcelDTO);
}

return qualityAlarmExcel;
}
}

4.效果图

通过身高体重计算是否健康

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>BMI 计算器</title>
<style>
body {
font-family: "Helvetica Neue", sans-serif;
background: linear-gradient(to right, #f9f9f9, #e2f0ff);
padding: 30px;
margin: 0;
}

.container {
max-width: 400px;
margin: 0 auto;
background: #fff;
padding: 24px;
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
text-align: center;
margin-bottom: 24px;
color: #0078d7;
}

label {
display: block;
margin-top: 12px;
font-weight: bold;
}

input {
width: 100%;
padding: 10px;
margin-top: 6px;
border-radius: 8px;
border: 1px solid #ccc;
box-sizing: border-box;
}

button {
width: 100%;
margin-top: 20px;
padding: 12px;
background-color: #0078d7;
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
}

button:hover {
background-color: #005fa3;
}

.result {
margin-top: 20px;
text-align: center;
font-size: 18px;
color: #333;
}
</style>
</head>
<body>
<div class="container">
<h2>BMI 计算器</h2>

<label for="height">身高(厘米):</label>
<input type="number" id="height" placeholder="请输入您的身高,如 170">

<label for="weight">体重(斤):</label>
<input type="number" id="weight" placeholder="请输入您的体重,如 130">

<button onclick="calculateBMI()">开始计算</button>

<div class="result" id="result"></div>
</div>

<script>
function calculateBMI() {
const height = parseFloat(document.getElementById("height").value);
const weightJin = parseFloat(document.getElementById("weight").value);
const resultEl = document.getElementById("result");

if (!height || !weightJin || height <= 0 || weightJin <= 0) {
resultEl.textContent = "请输入正确的身高和体重!";
return;
}

const weightKg = weightJin / 2;
const heightM = height / 100;
const bmi = weightKg / (heightM * heightM);
let status = "";

if (bmi < 18.5) status = "过轻";
else if (bmi < 25) status = "正常";
else if (bmi < 28) status = "过重";
else if (bmi < 32) status = "肥胖";
else status = "严重肥胖";

resultEl.textContent = `您的 BMI 是 ${bmi.toFixed(2)},属于「${status}」`;
}
</script>
</body>
</html>

效果图

1. 输出

打印hello word!

输入python

“ “用,分隔可以输出多个

可直接做加减乘除运算

1
2
3
4
5
6
print("hello world!")
print("你好","美妙的世界")
print(100)
print(100+200)
print(100*200)
print(100/200)

2. 输入

用户输入后打印

1
2
3
4
name = input()
print(name)
print("hello",name)
name = input('please enter your name: ')

1 Java整合

1.1 获取第三方授权

首页-OpenAPI

进入金蝶云首页,点击开发指南,快速入门,有对应的教程

步骤一较为详细,可以参考

遇到的问题:测试时,只有集成的用户登录,才可以调用api进行修改。否则调用接口返回的链接会显示(会话信息已丢失,请重新登录)

解决方法:设置二次验权密码(后发现即使提出请重新登录,也可以修改数据)

1
2
3
4
5
6
X-KDApi-AcctID =6304ba61219bf5
X-KDApi-AppID=225649_7ZbM6dDO0qrVXXUKX/Xs09wH2u5d4rLE
X-KDApi-AppSec =2bb1d972f3574a46aebee03cdc80aeae
X-KDApi-UserName =demo
X-KDApi-LCID=2052
X-KDApi-ServerUrl=https://apiexp.open.kingdee.com/k3cloud/

1.2 下载使用SDK

SDK中心-OpenAPI

找到想要的jdk版本解压后即可,有一个demo可以测试

创建一个libs/kingdee目录,把jar包放入

创建一个kdwebapi.properties文件,写入登录授权获取到的数据

pom里面导入依赖

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.kingdee</groupId>
<artifactId>k3cloud-webapi</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/libs/kingdee/k3cloud-webapi-8.2.0.jar</systemPath>
</dependency>

测试

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) {
K3CloudApi client = new K3CloudApi();
String jsonData = "{\"FormId\":\"\",\"FieldKeys\":\"\",\"FilterString\":\"\"," +
"\"OrderString\":\"\",\"TopRowCount\":0,\"StartRow\":0,\"Limit\":0}";
JSONObject jsonObject = JSONObject.parseObject(jsonData);
//组织机构查询接口ID
jsonObject.put("FormId", "ORG_Organizations");
//需要获得的字段信息
jsonObject.put("FieldKeys", "FNumber,FName,FDescription,FAcctOrgType,FContact");
jsonObject.put("Limit", 10);
try {
List<List<Object>> result = client.executeBillQuery(jsonObject.toJSONString());
for (List<Object> obj : result) {
System.out.println(obj.toString());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

整合完毕

参考文章:Java Maven项目对接金蝶SDK_kdwebapi.properties-CSDN博客

2 api的使用

官方接口文档

API文档-OpenAPI

2.1 查询

此处以委托单为例

先查到单据编号FBillNo,再通过单据编号查到整个单据的结构,再根据自己的业务需求获取到对应的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class JinDieYunApi {

//获取检验单编号
//每种单据类型都有对应的FormId,可在api文档查看
//FieldKeys为要查询的类型
//查询条件0代表所有的
//json格式一定要注意!
public static List<JSONObject> Codes() throws Exception {
var api = new K3CloudApi();
String json = "{\n" +
" \"FormId\": \"QM_InspectBill\",\n" + // 检验单 FormId
" \"FieldKeys\": \"FBillNo\", \n" + //
" \"FilterString\": \"\", \n" +
" \"OrderString\": \"\", \n" +
" \"TopRowCount\": 0, \n" +
" \"StartRow\": 0, \n" +
" \"Limit\": 0, \n" +
" \"SubSystemId\": \"\" \n" +
"}";

String result = api.billQuery(json);
System.out.println("检验单查询接口: " + result);

List<JSONObject> jsonArrays = JSON.parseArray(result, JSONObject.class);

return jsonArrays;
}
}

实体类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@Data
public class Fbill extends BaseEntity
{
private static final long serialVersionUID = 1L;

/** $column.columnComment */
private Long id;

/** 单据主键 */
private String fid;

/** 单据状态 */
private String status;


/** 单据编号 */
private String fBillno;


/** 物料id */
private String fMaterialId;

/** 物料名称 */
private String fMaterialName;

/** 物料编码 */
private String fMaterialNumber;

/** 检验数量 */
private String fInspectQty;

/** 合格数 */
private String fQualifiedQty;

/** 不合格数 */
private String fUnqualifiedQty;

/** 物料码 */
private String fCode;

/** 删除标识 */
private String delFlag;

/** 内部批次号 */
private String fEntityId;

/** 合格数id */
private String qualifiedId;

/** 不合格数id */
private String unqualifiedId;

/** 描述 */
private String fDescription;

/** 创建时间 */
private Date createTime;

}

api.view用于查看表的结构,获取自己想要的数据,可以添加到自己的数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import org.junit.Test;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
public class Demo {
@Test
public void test() throws Exception {
List<JSONObject> codes = JinDieYunApi.Codes();

K3CloudApi api = new K3CloudApi();

for (JSONObject obj : codes) {
System.out.println(obj.toString());
String formId = "QM_InspectBill";
String FBillNo = obj.getString("FBillNo"); // 表单标识:检验单
String aa = "{" +
"\"CreateOrgId\": 0," +
"\"Number\": \"" + FBillNo + "\"," +
"\"Id\": \"\"" +
"}";

String json = api.view(formId, aa); //查看整个表的结构

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);

JsonNode resultNode = root.path("Result").path("Result");
int size = root.path("Result").path("Result").path("Entity").size();

for (int i = 0; i < size; i++) {
Fbill fbill = new Fbill();
//获取单据的信息
JsonNode Entity = root.path("Result").path("Result").path("Entity").get(i);
JsonNode PolicyDetail = root.path("Result").path("Result").path("Entity").get(i).path("PolicyDetail");
int PolicyDetailSize = root.path("Result").path("Result").path("Entity").get(i).path("PolicyDetail").size();

JsonNode MaterialId = root.path("Result").path("Result").path("Entity").get(i).path("MaterialId");
JsonNode name = root.path("Result").path("Result").path("Entity").get(i).path("MaterialId").path("Name").get(0);

String createDate = resultNode.path("CreateDate").asText();
String billNo = resultNode.path("BillNo").asText();
String description = resultNode.path("Description").asText();
String fid = resultNode.path("Id").asText();
String entityId = Entity.path("Id").asText();
String materialId = Entity.path("MaterialId_Id").asText();
String inspectQty = Entity.path("InspectQty").asText();
String qualifiedQty = Entity.path("QualifiedQty").asText();
String unqualifiedQty = Entity.path("UnqualifiedQty").asText();
String materialNumber = MaterialId.path("Number").asText();
String materialName = name.path("Value").asText();

System.out.println(PolicyDetailSize);
for (int j = 0; j < PolicyDetailSize; j++) {
String status = PolicyDetail.get(j).path("PolicyStatus").asText();
if ("1".equals(status)) {
String qualifiedId = PolicyDetail.get(j).path("Id").asText();
System.out.println("合格数id:" + qualifiedId);
fbill.setQualifiedId(qualifiedId);
}
if ("2".equals(status)) {
String unqualifiedId = PolicyDetail.get(j).path("Id").asText();
System.out.println("不合格数id:" + unqualifiedId);
fbill.setUnqualifiedId(unqualifiedId);
}

}


// 1. 解析 ISO 时间格式
LocalDateTime localDateTime = LocalDateTime.parse(createDate);

// 2. 转为 java.util.Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

fbill.setCreateTime(date);
fbill.setFid(fid);
fbill.setfBillno(billNo);
fbill.setfMaterialId(materialId);
fbill.setfMaterialName(materialName);
fbill.setfDescription(description);
fbill.setfInspectQty(inspectQty);
fbill.setfQualifiedQty(qualifiedQty);
fbill.setfUnqualifiedQty(unqualifiedQty);
fbill.setfEntityId(entityId);
fbill.setfMaterialNumber(materialNumber);

System.out.println("转换后的 Date 对象:" + date);
System.out.println("创建时间:" + createDate);
System.out.println("单据编号:" + billNo);
System.out.println("wuliaoid:" + materialId);
System.out.println("Id:" + fid);
System.out.println("物料实体id:" + entityId);
System.out.println("物料编码:" + materialNumber);
System.out.println("MaterialName:" + materialName);
System.out.println("描述:" + description);
System.out.println("检验数量:" + inspectQty);
System.out.println("合格数量:" + qualifiedQty);
System.out.println("不合格数量:" + unqualifiedQty);

System.out.println("-------------------------------");

System.out.println("-------------------------------");


}
}
}
}

2.2 修改

此处展示了两种写法,推荐第二种。一定注意格式

这里的业务展示的是对检验单合格数与不合格数的修改,委托单里有两个及以上收料通知单的话,必须要把全部的收料通知单的数据都写上,(金蝶云是把原来的都删除,再新增,如果只修改一个,其余的数据都会被覆盖)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
public  void firstUpdateDocument(Fbill firstBill) throws Exception {
var api = new K3CloudApi();

Fbill fbill = new Fbill();
fbill.setFid(firstBill.getFid());
List<Fbill> fbills = fbillMapper.selectFbillList(fbill);

if (fbills.isEmpty()){
return ;
}

JSONArray entityArray = new JSONArray();
JSONObject model = new JSONObject();
model.put("FID", firstBill.getFid());
model.put("FDescription", firstBill.getfDescription());
//遍历所有的编号
for (Fbill bill:fbills){
JSONObject entry = new JSONObject();
entry.put("FEntryID", Integer.parseInt(bill.getfEntityId()));
entry.put("FInspectQty", Double.parseDouble(bill.getfInspectQty()));
if (bill.getfEntityId().equals(firstBill.getfEntityId())){
entry.put("FQualifiedQty", Double.parseDouble(firstBill.getfQualifiedQty()));
entry.put("FUnqualifiedQty", Double.parseDouble(firstBill.getfUnqualifiedQty()));
}else {
entry.put("FQualifiedQty", Double.parseDouble(bill.getfQualifiedQty()));
entry.put("FUnqualifiedQty", Double.parseDouble(bill.getfUnqualifiedQty()));
}

entityArray.add(entry);
}

model.put("FEntity", entityArray);

JSONObject request = new JSONObject();
request.put("NeedUpDateFields", Arrays.asList("FDescription", "FQualifiedQty", "FInspectQty", "FUnqualifiedQty"));
request.put("IsAutoAdjustField", true);
request.put("Model", model);

String json = request.toJSONString();
System.out.println("构建的JSON: " + json);

String result = api.save("QM_InspectBill", json);
System.out.println(result);


}




public viod updateDocument(Fbill updateFbill) throws Exception {
var api = new K3CloudApi();

Fbill fbill = new Fbill();
fbill.setFid(updateFbill.getFid());
List<Fbill> fbills = fbillMapper.selectFbillList(fbill);

if (fbills.isEmpty()) {
return ;
}

StringBuilder entityBuilder = new StringBuilder();
for (int i = 0; i < fbills.size(); i++) {
Fbill bill = fbills.get(i);

StringBuilder policyDetailBuilder = new StringBuilder();
if (bill.getfEntityId().equals(updateFbill.getfEntityId())){
if ("0".equals(updateFbill.getfQualifiedQty())){
updateFbill.setQualifiedId(null);
}
if ("0".equals(updateFbill.getfUnqualifiedQty())){
updateFbill.setUnqualifiedId(null);
}
if (updateFbill.getQualifiedId() != null) {
policyDetailBuilder.append("{")
.append("\"FDetailID\": ").append(updateFbill.getQualifiedId()).append(", ")
.append("\"FPolicyQty\": ").append(updateFbill.getfQualifiedQty()).append(", ")
.append("\"FPolicyType\": \"1\"")
.append("},");
}
if (updateFbill.getUnqualifiedId() != null) {
policyDetailBuilder.append("{")
.append("\"FDetailID\": ").append(updateFbill.getUnqualifiedId()).append(", ")
.append("\"FPolicyQty\": ").append(updateFbill.getfUnqualifiedQty()).append(", ")
.append("\"FPolicyType\": \"2\"")
.append("},");
}
}else {
if (bill.getQualifiedId() != null) {
policyDetailBuilder.append("{")
.append("\"FDetailID\": ").append(bill.getQualifiedId()).append(", ")
.append("\"FPolicyQty\": ").append(bill.getfQualifiedQty()).append(", ")
.append("\"FPolicyType\": \"1\"")
.append("},");
}
if (bill.getUnqualifiedId() != null) {
policyDetailBuilder.append("{")
.append("\"FDetailID\": ").append(bill.getUnqualifiedId()).append(", ")
.append("\"FPolicyQty\": ").append(bill.getfUnqualifiedQty()).append(", ")
.append("\"FPolicyType\": \"2\"")
.append("},");
}
}


// 移除最后一个逗号
if (policyDetailBuilder.length() > 0 && policyDetailBuilder.charAt(policyDetailBuilder.length() - 1) == ',') {
policyDetailBuilder.setLength(policyDetailBuilder.length() - 1);
}

entityBuilder.append("{")
.append("\"FEntryID\": ").append(bill.getfEntityId()).append(", ")
.append("\"FPolicyDetail\": [").append(policyDetailBuilder).append("]")
.append("}");

if (i != fbills.size() - 1) {
entityBuilder.append(",");
}
}

// 拼接最终 JSON
String json = "{" +
"\"NeedUpDateFields\": [\"FDescription\", \"FQualifiedQty\", \"FPolicyQty\"]," +
"\"IsAutoAdjustField\": true," +
"\"Model\": {" +
"\"FID\": " + updateFbill.getFid() + "," +
"\"FDescription\": \"" + updateFbill.getfDescription() + "\"," +
"\"FEntity\": [" + entityBuilder + "]" +
"}" +
"}";

System.out.println("最终构建JSON: " + json);

String result = api.save("QM_InspectBill", json);
System.out.println("第一次调用结果: " + result);


}

npm导入

默认导入是最新版本,必须选定版本号才可登录

1
npm show three versions  

查看所有的版本

找到符合vue2的版本进行下载

1
npm install three@0.126.1 --save

vue代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
 
<div ref="container" style="width: 100%; height: 600px; position: relative; top: -300px;" class="threeD"></div>


// 导入 Three.js 主模块
import * as THREE from 'three'
// 从 three/examples/jsm 目录导入 GLTFLoader(three@0.126.1 已支持ES模块导入)
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

// 导入 OrbitControls 用于交互旋转和缩放
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

data() {
return {
scene: null,
camera: null,
renderer: null,
loader: null,
model: null,
controls: null,
animationId: null,
raycaster: new THREE.Raycaster(),
mouse: new THREE.Vector2(),
selectedObject: null,
}


mounted() {

this.initScene();
this.loadModel();
this.animate();
window.addEventListener('resize', this.onResize);
this.$refs.container.addEventListener('click', this.onClick, false);
},
beforeDestroy() {
// 清除窗口事件监听和动画循环
window.removeEventListener('resize', this.onResize);
cancelAnimationFrame(this.animationId);
if (this.renderer) {
this.renderer.dispose();
}
},
methods: {
// 初始化场景、相机、光照和渲染器,并配置 OrbitControls
initScene() {
const container = this.$refs.container;
const width = container.clientWidth;
const height = container.clientHeight;

// 创建场景
this.scene = new THREE.Scene();

// 创建透视相机
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
// 设置俯视视角:相机高高在上,y = 20,z = 0
// this.camera.position.set(100, 60, 200);
this.camera.position.set(25,15,50);

// 让相机朝下看
this.camera.lookAt(new THREE.Vector3(0,0,0));
this.scene.add(this.camera);


// 添加环境光和方向光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
this.scene.add(ambientLight);

const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 7.5);
this.scene.add(directionalLight);

// 创建渲染器,开启抗锯齿与透明背景
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
this.renderer.setSize(width, height);
container.appendChild(this.renderer.domElement);

// 初始化 OrbitControls 实例,关联相机和渲染器 DOM 元素
this.controls = new OrbitControls(this.camera, this.renderer.domElement);
// 开启阻尼效果,提升控制的流畅性
this.controls.enableDamping = true;
this.controls.dampingFactor = 0.25;
// 允许缩放(可选)
this.controls.enableZoom = true;
},
// 使用 GLTFLoader 加载 GLB 模型
loadModel() {
this.loader = new GLTFLoader();
// 模型文件放在 public/models 目录下
this.loader.load(
'/models/model.glb',
(gltf) => {
this.model = gltf.scene;
// 根据需要调整模型的缩放、位置及旋转
this.model.scale.set(1, 1, 1);
this.model.position.set(0, 0, 0);
this.scene.add(this.model);
},
(xhr) => {
console.log(`模型加载进度:${(xhr.loaded / xhr.total) * 100}%`);
},
(error) => {
console.error('加载 GLB 模型出错:', error);
}
);
},
// 动画循环,更新控制器和渲染场景
animate() {
this.animationId = requestAnimationFrame(this.animate);
// 更新 OrbitControls,确保交互效果平滑
if (this.controls) {
this.controls.update();
}
this.renderer.render(this.scene, this.camera);
},
// 监听窗口大小变化,调整相机和渲染器
onResize() {
const container = this.$refs.container;
const width = container.clientWidth;
const height = container.clientHeight;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
},

// 点击事件处理
onClick(event) {
const rect = this.$refs.container.getBoundingClientRect();
// 计算鼠标点击位置归一化坐标(-1 到 1)
this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;

this.raycaster.setFromCamera(this.mouse, this.camera);

// 获取所有可拾取的模型子对象
const intersects = this.raycaster.intersectObjects(this.model.children, true);

if (intersects.length > 0) {
const selected = intersects[0].object;
this.selectedObject = selected;

console.log('点击了对象:', selected.name || selected.uuid);

// 可选:显示提示信息
// alert(`你点击了部件:${selected.name || '未命名对象'}`);
}
},
}
}

模型文件放在 public/models 目录下。 ‘/models/model.glb’, 替换名字即可

以下是效果图

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment