c#将excel数据录入数组
时间: 2023-07-14 09:13:56 浏览: 88
C#把excel表格中的数据读入到数组
4星 · 用户满意度95%
您可以使用以下代码将 Excel 数据录入到 C# 数组中:
1. 安装 `Microsoft.Office.Interop.Excel` 库。
2. 引用命名空间 `using Microsoft.Office.Interop.Excel;`
3. 打开 Excel 文件并获取工作表:
```csharp
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
Worksheet worksheet = workbook.Worksheets[1];
```
4. 获取数据范围:
```csharp
Range range = worksheet.UsedRange;
```
5. 获取数据范围的行数和列数:
```csharp
int rows = range.Rows.Count;
int columns = range.Columns.Count;
```
6. 创建数组并将数据录入:
```csharp
string[,] data = new string[rows, columns];
for (int row = 1; row <= rows; row++)
{
for (int column = 1; column <= columns; column++)
{
Range cell = range.Cells[row, column];
if (cell.Value2 != null)
{
data[row - 1, column - 1] = cell.Value2.ToString();
}
}
}
```
完整代码如下:
```csharp
using Microsoft.Office.Interop.Excel;
...
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
Worksheet worksheet = workbook.Worksheets[1];
Range range = worksheet.UsedRange;
int rows = range.Rows.Count;
int columns = range.Columns.Count;
string[,] data = new string[rows, columns];
for (int row = 1; row <= rows; row++)
{
for (int column = 1; column <= columns; column++)
{
Range cell = range.Cells[row, column];
if (cell.Value2 != null)
{
data[row - 1, column - 1] = cell.Value2.ToString();
}
}
}
workbook.Close();
excel.Quit();
```
请注意,在使用完 Excel 后,您需要关闭工作簿和 Excel 应用程序。
阅读全文