如何使用c#导入Excel
时间: 2023-11-11 12:07:04 浏览: 39
可以使用以下步骤在 C# 中导入 Excel:
1. 首先,需要安装 Microsoft.Office.Interop.Excel 包。
2. 在代码中添加以下命名空间:
```csharp
using Microsoft.Office.Interop.Excel;
```
3. 创建一个 Excel 应用程序对象:
```csharp
Application excel = new Application();
```
4. 打开 Excel 文件:
```csharp
Workbook workbook = excel.Workbooks.Open(@"C:\path\to\file.xlsx");
```
5. 获取 Excel 工作表:
```csharp
Worksheet worksheet = workbook.Sheets[1];
```
6. 读取单元格的值:
```csharp
Range range = worksheet.Cells[row, column];
string value = range.Value.ToString();
```
7. 关闭 Excel 文件:
```csharp
workbook.Close(false, Type.Missing, Type.Missing);
```
8. 释放 Excel 应用程序对象:
```csharp
excel.Quit();
Marshal.ReleaseComObject(excel);
```
完整示例代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace ExcelReader
{
class Program
{
static void Main(string[] args)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\path\to\file.xlsx");
Worksheet worksheet = workbook.Sheets[1];
Range range = worksheet.Cells[1, 1];
string value = range.Value.ToString();
workbook.Close(false, Type.Missing, Type.Missing);
excel.Quit();
Marshal.ReleaseComObject(excel);
}
}
}
```