C#读取Excel以及将数据导入至Excel
时间: 2023-08-19 15:05:03 浏览: 267
好的,这是一个关于C#读取和导入Excel的问题,我可以提供一些帮助。
首先,你需要在C#中安装Excel Interop。在Visual Studio中打开你的项目,然后在“工具”菜单中选择“NuGet 包管理器”,搜索“Microsoft.Office.Interop.Excel”并安装。
读取Excel数据:
```
using Microsoft.Office.Interop.Excel;
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open("path/to/excel/file.xlsx");
Worksheet worksheet = workbook.Worksheets[1];
Range range = worksheet.UsedRange;
for (int row = 1; row <= range.Rows.Count; row++)
{
for (int col = 1; col <= range.Columns.Count; col++)
{
string cellValue = range.Cells[row, col].Value2.ToString();
Console.WriteLine(cellValue);
}
}
```
将数据导入Excel:
```
using Microsoft.Office.Interop.Excel;
Application excel = new Application();
Workbook workbook = excel.Workbooks.Add(Type.Missing);
Worksheet worksheet = (Worksheet)workbook.ActiveSheet;
for (int row = 1; row <= data.Rows.Count; row++)
{
for (int col = 1; col <= data.Columns.Count; col++)
{
worksheet.Cells[row, col] = data.Rows[row - 1][col - 1].ToString();
}
}
workbook.SaveAs("path/to/excel/file.xlsx");
workbook.Close();
excel.Quit();
```
这些代码可以读取Excel文件中的所有单元格值,并将数据导入到新的Excel文件中。你可以根据自己的需求修改代码。
阅读全文
相关推荐


















