下面是一个使用C#操作Excel的示例代码:

using System;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建Excel对象
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook workbook = excelApp.Workbooks.Add();
            Excel.Worksheet worksheet = workbook.ActiveSheet;

            // 写入数据
            worksheet.Cells[1, 1] = "姓名";
            worksheet.Cells[1, 2] = "年龄";
            worksheet.Cells[2, 1] = "张三";
            worksheet.Cells[2, 2] = "20";
            worksheet.Cells[3, 1] = "李四";
            worksheet.Cells[3, 2] = "25";

            // 保存Excel文件
            string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "sample.xlsx");
            workbook.SaveAs(filePath);

            // 关闭Excel对象
            workbook.Close();
            excelApp.Quit();

            Console.WriteLine("Excel文件已保存到桌面上的sample.xlsx");
            Console.ReadLine();
        }
    }
}

在这个示例中,我们使用了Microsoft.Office.Interop.Excel命名空间中的类来操作Excel文件。首先创建了一个Excel对象,然后创建一个工作簿和一个工作表,将数据写入工作表中,最后保存Excel文件并关闭Excel对象。请确保已安装Microsoft Office并添加对Microsoft.Office.Interop.Excel的引用

用C#写出操作excel代码

原文地址: https://www.cveoy.top/t/topic/igz9 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录