C# 读取EXCEL并返回DataTable使用using Microsoft.Office.Interop.Excel
时间: 2024-04-30 19:18:33 浏览: 214
使用 Microsoft.Office.Interop.Excel 可以读取 Excel 文件并将数据存储在 DataTable 中。以下是一个示例代码,它打开一个 Excel 文件,将其转换为 DataTable,并关闭 Excel 应用程序。
```csharp
using System.Data;
using Microsoft.Office.Interop.Excel;
public DataTable ReadExcel(string filePath)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(filePath);
Worksheet worksheet = workbook.ActiveSheet;
Range range = worksheet.UsedRange;
DataTable dataTable = new DataTable();
for (int i = 1; i <= range.Columns.Count; i++)
{
DataColumn dataColumn = new DataColumn();
dataColumn.ColumnName = "Column" + i;
dataTable.Columns.Add(dataColumn);
}
for (int i = 1; i <= range.Rows.Count; i++)
{
DataRow dataRow = dataTable.NewRow();
for (int j = 1; j <= range.Columns.Count; j++)
{
dataRow["Column" + j] = range.Cells[i, j].Value2.ToString();
}
dataTable.Rows.Add(dataRow);
}
workbook.Close(false);
excel.Quit();
return dataTable;
}
```
请注意,此代码需要将 Microsoft.Office.Interop.Excel 添加到项目的引用中。
阅读全文