C#连接并操作excel
时间: 2024-09-14 07:13:51 浏览: 33
c#连接excel示例分享
在C#中,可以使用Microsoft.Office.Interop.Excel命名空间中的类库来连接和操作Excel文件。以下是一个简单的步骤概述:
1. 引入必要的命名空间:
```csharp
using Microsoft.Office.Interop.Excel;
```
2. 创建Excel应用程序实例:
```csharp
Application excelApp = new Application();
```
3. 检查并启用COM支持(如果尚未启用):
```csharp
Type objType = Type.GetTypeFromProgID("Excel.Application");
objType.InvokeMember("Visible", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.SetProperty, null, excelApp, false);
```
4. 打开或创建工作簿:
```csharp
Workbook workbook = excelApp.Workbooks.Add();
```
5. 访问或修改工作表:
```csharp
Worksheet worksheet = workbook.ActiveSheet;
string cellValue = worksheet.Cells[1, 1].Value; // 读取单元格值
worksheet.Cells[1, 1].Value = "Hello"; // 写入新的值
```
6. 关闭工作簿和退出应用:
```csharp
workbook.SaveAs("路径\to\your\file.xlsx");
workbook.Close();
excelApp.Quit();
```
7. 锁定释放对Office对象的引用,防止内存泄漏:
```csharp
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excelApp);
```
阅读全文