111,094
社区成员




代码
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();
workbook = excelApp.Workbooks.Add();
worksheet = (Worksheet)workbook.Sheets[1];
// 设置Timer,每隔1000毫秒(1秒)触发一次Elapsed事件
timer = new Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
Console.WriteLine("Press [Enter] to exit the program.");
Console.ReadLine();
// 释放资源
DisposeExcelResources();
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
// 生成一些示例数据
string data = $"Data at {DateTime.Now}";
// 写入数据到Excel
worksheet.Cells[row, 1] = data;
row++;
// 确保Excel能够显示最新的数据(可选)
excelApp.Visible = true;
}
private static void DisposeExcelResources()
{
// 释放Excel资源
if (workbook != null)
{
workbook.Close(false, Type.Missing, Type.Missing);
Marshal.ReleaseComObject(workbook);
}
if (excelApp != null)
{
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
// 释放Timer资源
timer.Dispose();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
运行完在工程目录找不到excel文件。
请问专家,怎么回事?谢谢
Excel文件没有保存到disk
string filePath = @"C:\path\to\your\directory\example.xlsx"; // 替换为实际路径
if (workbook != null)
{
workbook.SaveAs(filePath); // 保存
workbook.Close(false, Type.Missing, Type.Missing);
Marshal.ReleaseComObject(workbook);
}