这个代码运行没问题生不成EXCEL文件

ccbbcc 2024-10-22 14:18:13

代码

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文件。

请问专家,怎么回事?谢谢

...全文
86 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
gsubbdjjbg8296 2024-11-03
  • 打赏
  • 举报
回复 1

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);
}

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧