代碼:
[AppleScript] 純文本查看 復制代碼 using System;
using System.Timers;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
class Program
{
private static Timer _timer;
private static Application _excelApp;
private static Workbook _workbook;
private static _Worksheet _worksheet;
private static int _row = 1; // 初始行號
static void Main(string[] args)
{
// 初始化Excel應用程序
_excelApp = new Application();
_excelApp.Visible = true; // 如果需要可見,否則設置為false
_workbook = _excelApp.Workbooks.Add();
_worksheet = (_Worksheet)_workbook.Sheets[1];
// 設置定時器
_timer = new Timer(1000); // 1000毫秒 = 1秒
_timer.Elapsed += OnTimedEvent;
_timer.AutoReset = true;
_timer.Enabled = true;
Console.WriteLine("按Enter鍵退出程序...");
Console.ReadLine();
// 清理資源
_timer.Stop();
_timer.Dispose();
// 關閉Excel并釋放資源
Marshal.ReleaseComObject(_worksheet);
Marshal.ReleaseComObject(_workbook);
_excelApp.Quit();
Marshal.ReleaseComObject(_excelApp);
GC.Collect();
GC.WaitForPendingFinalizers();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// 生成隨機數據
Random rand = new Random();
int randomValue = rand.Next(1, 100);
// 寫入數據到Excel
_worksheet.Cells[_row, 1] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_worksheet.Cells[_row, 2] = randomValue;
// 更新行號
_row++;
}
}
這是文心一言自動生成的,運行沒提示錯誤,可是找不到excel文件,也不知道EXCEL文件的名字。
請高手指教,謝謝
|