以下是使用C#读写Excel批量单元格的代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelReadWriteExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建Excel应用程序对象
            Excel.Application excelApp = new Excel.Application();

            // 打开Excel文件
            Excel.Workbook workbook = excelApp.Workbooks.Open(@"D:\example.xlsx");

            // 获取第一个工作簿
            Excel.Worksheet worksheet = workbook.Sheets[1];

            // 读取单元格数据
            string cellValue = worksheet.Cells[1, 1].Value.ToString();
            Console.WriteLine("当前单元格的值为:" + cellValue);

            // 写入单元格数据
            worksheet.Cells[1, 1].Value = "Hello World";

            // 保存并关闭Excel文件
            workbook.Save();
            workbook.Close();

            // 退出Excel应用程序
            excelApp.Quit();

            Console.WriteLine("操作完成。");
            Console.ReadLine();
        }
    }
}

以上代码使用了Microsoft.Office.Interop.Excel命名空间中的类来操作Excel文件。首先,使用Excel.Application创建了一个Excel应用程序对象。然后,使用Open方法打开指定的Excel文件。接下来,通过Sheets属性获取指定的工作簿,再通过Cells属性读取或写入特定单元格的数据。最后,使用Save方法保存文件,使用Close方法关闭文件,使用Quit方法退出Excel应用程序。

请注意,在运行此代码之前,需要在项目中添加对Microsoft.Office.Interop.Excel的引用。可以在Visual Studio的“解决方案资源管理器”中右键点击“引用”,然后选择“添加引用”,在“COM”选项卡中找到并勾选“Microsoft Excel xx.x Object Library”(根据您的Excel版本选择对应的库),点击“确定”按钮即可添加引用

写出C#读写exce批量l单元格的代码

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

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