C#读取Excel以及将数据导入至Excel
时间: 2024-05-16 16:15:06 浏览: 10
在 C# 中,可以使用 Microsoft.Office.Interop.Excel 库来读取和写入 Excel 文件。以下是一个简单的示例,演示了如何读取 Excel 文件中的数据并将数据写入 Excel 文件中。
首先,需要在项目中添加对 Microsoft.Office.Interop.Excel 库的引用。然后,在代码中使用以下命名空间:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
```
读取 Excel 文件的数据:
```csharp
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
Excel.Worksheet sheet = workbook.ActiveSheet;
// 获取行数和列数
int rowCount = sheet.UsedRange.Rows.Count;
int columnCount = sheet.UsedRange.Columns.Count;
// 循环遍历所有单元格
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= columnCount; j++)
{
Excel.Range cell = sheet.Cells[i, j];
string value = cell.Value.ToString();
Console.WriteLine(value);
}
}
```
将数据写入 Excel 文件:
```csharp
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add();
Excel.Worksheet sheet = workbook.ActiveSheet;
// 写入数据
sheet.Cells[1, 1] = "Name";
sheet.Cells[1, 2] = "Age";
sheet.Cells[2, 1] = "John";
sheet.Cells[2, 2] = 30;
sheet.Cells[3, 1] = "Mary";
sheet.Cells[3, 2] = 25;
// 保存文件
workbook.SaveAs(@"C:\example.xlsx");
workbook.Close();
excel.Quit();
```
以上示例仅为基础示例,实际应用中需要根据具体需求进行修改和优化。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)