electron初学之随机点名

这篇博客介绍了如何利用Electron框架开发一个点名应用程序。作者首先展示了如何读取Excel表格中的姓名数据并存储,然后详细讲解了应用的窗口配置、事件监听以及随机点名功能的实现。应用支持按班级读取Excel文件,随机展示点名,并提供了安装程序的创建配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近学了下electron,实践下也弄个exe安装程序。

思路:按照每个班级提供一个表格,读取表格中姓名列内容,存储一下。点名时选择班级,对班级人员随机展示,实现点名

主要配置

async function createWindow() {
	// Create the browser window.
	const win = new BrowserWindow({
		width: 800,
		height: 600,
		webPreferences: {
			webSecurity: false, //取消跨域限制
			// Use pluginOptions.nodeIntegration, leave this alone
			// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
			nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
			contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
			enableRemoteModule: true
		},
		// eslint-disable-next-line no-undef
		icon: `${__static}/ept.ico`,
		// titleBarStyle: "hidden-inset", //隐藏标题栏
		autoHideMenuBar: true, //隐藏菜单栏
		//frame: false, //无边框
		// titleBarOverlay: true, //显示关闭最大化最小化
		resizable: false, //是否可以改变窗口size,默认为 true.
	});

	if (process.env.WEBPACK_DEV_SERVER_URL) {
		// Load the url of the dev server if in development mode
		await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
		if (!process.env.IS_TEST) win.webContents.openDevTools();
	} else {
		createProtocol("app");
		// Load the index.html when not in development
		win.loadURL("app://./index.html");
	}
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
	// On macOS it is common for applications and their menu bar
	// to stay active until the user quits explicitly with Cmd + Q
	if (process.platform !== "darwin") {
		app.quit();
	}
	// 生产模式下在关闭electron时,启动stop.bat把java进程也关闭
	if (isCopyLib && !isDevelopment) {
		shell.openPath(path.resolve() + "\\resources\\lib\\stop.bat");
	}
});

app.on("activate", () => {
	// On macOS it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
	//生产模式下启动时打开运行bat启动java进程
	if (isCopyLib && !isDevelopment) {
		shell.openPath(path.resolve() + "\\resources\\lib\\run.bat");
	}
	createWindow();
});
pluginOptions: {
		electronBuilder: {
			nodeIntegration: true,
			contextIsolation: false,
			enableRemoteModule: true,
			builderOptions: {
				appId: "com.example.app",
				productName: appName, //项目名,也是生成的安装文件名,即aDemo.exe
				copyright: "Copyright © 2022 HiCB", //版权信息
				//打包时复制项目目录下的res中文文件到 打包后的exe所在目录的res文件夹中,文件夹下没有文件的话不会复制
				extraResources: isCopyLib ? [{
					"from": "./lib/",
					"to": "../resources/lib"  
				}] : [],
				win: {
					//win相关配置
					icon: "./public/ept.ico", //图标,当前图标在根目录下,注意这里有两个坑
					target: [
						{
							target: "nsis", //利用nsis制作安装程序
							arch: [
								"x64", //64位
								"ia32"//32位
							],
						},
					],
				},
				nsis: {
					oneClick: false, // 是否一键安装
					allowElevation: true, // 允许请求提升。 如果为false,则用户必须使用提升的权限重新启动安装程序。
					allowToChangeInstallationDirectory: true, // 允许修改安装目录
					installerIcon: "./public/ept.ico", // 安装图标
					uninstallerIcon: "./public/ept.ico", //卸载图标
					installerHeaderIcon: "./public/ept.ico", // 安装时头部图标
					createDesktopShortcut: true, // 创建桌面图标
					createStartMenuShortcut: true, // 创建开始菜单图标
					shortcutName: appName, // 图标名称
				},
			},
		},
	},

读取表格中的姓名列,并进行存储

  readExcel1(file) {
      let that = this;
      if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message.error("上传格式不正确,请上传xls或者xlsx格式");
        this.clearFiles();
        return false;
      }
      const fileReader = new FileReader();
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result;
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          let name = file.name;
          that.fileName = name.substring(0, name.indexOf("."));
          that.readData(workbook);
        } catch (e) {
          return false;
        } finally {
          that.clearFiles();
        }
      };
      fileReader.readAsBinaryString(file);
    },
    readData(workbook) {
      const wsname = workbook.SheetNames[0]; //取第一张表
      const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], {
        range: 0,
      }); //生成json表格内容,从第一行开始(可以忽略标题)
      this.rawData = ws;
      let arr = [];
      for (let i = 0; i < ws.length; i++) {
        let item = ws[i]["姓名"];
        if (!isEmpty(item)) {
          arr.push(item);
        }
      }
      if (arr.length > 0) {
        let key = "myusers." + this.fileName;
        this.$setStoreData(key, arr);
        this.$emit("upload-success", ws);
        this.$baseMessage(
          "数据上传成功",
          "success",
          false,
          "vab-hey-message-success"
        );
      } else {
        this.$baseMessage(
          "未读取到【姓名】列,请检查是否存在【姓名】列并且是从第一行开始",
          "error",
          false,
          "vab-hey-message-error"
        );
      }
    },

按班级读取文件,随机点名

 handleStart() {
      if (this.users.length > 0) {
        this.sign = !this.sign;
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = "";
          // this.voicePrompt(this.user);
        } else {
          let that = this;
          this.timer = setInterval(() => {
            let index = that.randomNum(0, that.users.length - 1);
            that.user = that.users[index];
          }, 10);
        }
      } else {
        this.$baseMessage(
          "请先选择班级!",
          "error",
          false,
          "vab-hey-message-error"
        );
      }
    },
    //生成从minNum到maxNum的随机数
    randomNum(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10);
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        default:
          return 0;
      }
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值