代码:
[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文件的名字。
请高手指教,谢谢
|