.net导入,导出,操作EXCEL汇总
时间: 2023-08-16 07:06:08 浏览: 79
.net导入,导出excel
你可以使用C#语言中的Microsoft.Office.Interop.Excel库来操作Excel文件。
首先,你需要在Visual Studio中安装Microsoft.Office.Interop.Excel库。在安装完成后,你需要在项目中添加对Excel的引用。
导入Excel文件:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
Excel._Worksheet worksheet = workbook.Sheets[1];
Excel.Range range = worksheet.UsedRange;
for (int row = 1; row <= range.Rows.Count; row++)
{
for (int column = 1; column <= range.Columns.Count; column++)
{
string cellValue = range.Cells[row, column].Value.ToString();
Console.WriteLine(cellValue);
}
}
workbook.Close(false);
excel.Quit();
```
导出Excel文件:
```csharp
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Add();
Excel._Worksheet worksheet = workbook.Sheets[1];
for (int row = 1; row <= 10; row++)
{
for (int column = 1; column <= 10; column++)
{
worksheet.Cells[row, column] = row * column;
}
}
workbook.SaveAs(@"C:\example.xlsx");
workbook.Close();
excel.Quit();
```
以上代码演示了如何使用Microsoft.Office.Interop.Excel库来导入和导出Excel文件。你可以根据自己的需要对代码进行修改。
阅读全文