C# 打开EXCEL并保存
时间: 2023-07-27 13:08:54 浏览: 200
你可以使用 Microsoft.Office.Interop.Excel 库来打开和保存 Excel 文件。以下是一个示例代码:
```
using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace ExcelTest
{
class Program
{
static void Main(string[] args)
{
// 创建一个新的 Excel 实例
Application excel = new Application();
// 打开指定的 Excel 文件
Workbook workbook = excel.Workbooks.Open(@"C:\example.xlsx");
// 选中第一个工作表
Worksheet worksheet = workbook.Worksheets[1];
// 在 A1 单元格写入数据
Range range = worksheet.Cells[1, 1];
range.Value2 = "Hello, Excel!";
// 保存并关闭 Excel 文件
workbook.Save();
workbook.Close();
// 释放资源
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
excel = null;
workbook = null;
worksheet = null;
range = null;
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
```
注意:使用 Microsoft.Office.Interop.Excel 库需要安装 Microsoft Excel。如果你想在没有安装 Excel 的机器上运行程序,可以考虑使用其他的第三方库,例如 NPOI。
阅读全文
相关推荐















