wpf创建一个词典,键为excel的第一列中的数字,值为excel第二列的字符串
时间: 2024-02-28 10:56:31 浏览: 129
可以按照以下步骤来创建一个词典:
1. 引入以下命名空间:
```csharp
using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;
```
2. 声明一个 Dictionary 变量:
```csharp
Dictionary<int, string> dict = new Dictionary<int, string>();
```
3. 打开 Excel 文件并获取工作表:
```csharp
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open("excel文件路径");
Worksheet worksheet = workbook.Sheets[1];
```
4. 遍历 Excel 的第一列和第二列,并将它们作为键值对添加到词典中:
```csharp
int row = 1;
while (!string.IsNullOrEmpty(worksheet.Cells[row, 1].Text))
{
int key = (int)worksheet.Cells[row, 1].Value;
string value = worksheet.Cells[row, 2].Text;
dict.Add(key, value);
row++;
}
```
5. 关闭 Excel 文件:
```csharp
workbook.Close();
excel.Quit();
```
完整代码示例:
```csharp
using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;
// ...
Dictionary<int, string> dict = new Dictionary<int, string>();
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open("excel文件路径");
Worksheet worksheet = workbook.Sheets[1];
int row = 1;
while (!string.IsNullOrEmpty(worksheet.Cells[row, 1].Text))
{
int key = (int)worksheet.Cells[row, 1].Value;
string value = worksheet.Cells[row, 2].Text;
dict.Add(key, value);
row++;
}
workbook.Close();
excel.Quit();
```
阅读全文
相关推荐















