CSharp读取和写入Excel文件的方法和案例,包括具体实行步骤
时间: 2023-05-18 20:02:53 浏览: 138
Csharp读写Excel
5星 · 资源好评率100%
CSharp读取和写入Excel文件的方法和案例,包括具体实行步骤,可以使用Microsoft.Office.Interop.Excel库来实现。以下是一个简单的示例代码:
//引用Microsoft.Office.Interop.Excel库
using Microsoft.Office.Interop.Excel;
//读取Excel文件
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
Worksheet worksheet = workbook.Sheets[1];
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].Value2.ToString();
Console.Write(cellValue + "\t");
}
Console.WriteLine();
}
workbook.Close();
//写入Excel文件
Application excel = new Application();
Workbook workbook = excel.Workbooks.Add();
Worksheet worksheet = workbook.Sheets[1];
worksheet.Cells[1, 1] = "Hello";
worksheet.Cells[1, 2] = "World";
workbook.SaveAs(@"C:\example.xlsx");
workbook.Close();
注意:在使用Microsoft.Office.Interop.Excel库时,需要确保已经安装了Microsoft Office软件。
阅读全文