在.NET Core 3.1中打开Excel文件,编辑并另存为流的方法如下:
using Microsoft.Office.Interop.Excel;
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open("path/to/your/excel/file.xlsx");
请将"path/to/your/excel/file.xlsx"替换为你实际的Excel文件路径。
Worksheet worksheet = workbook.ActiveSheet;
Range cell = worksheet.Cells[1, 1]; // 获取第一个单元格
cell.Value = "Hello, World!"; // 修改单元格的值
MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
workbook.Close();
excelApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excelApp);
完整的代码示例:
using Microsoft.Office.Interop.Excel;
using System.IO;
using System.Runtime.InteropServices;
namespace ExcelManipulation
{
class Program
{
static void Main(string[] args)
{
Application excelApp = new Application();
Workbook workbook = excelApp.Workbooks.Open("path/to/your/excel/file.xlsx");
Worksheet worksheet = workbook.ActiveSheet;
Range cell = worksheet.Cells[1, 1];
cell.Value = "Hello, World!";
MemoryStream stream = new MemoryStream();
workbook.SaveAs(stream);
workbook.Close();
excelApp.Quit();
Marshal.ReleaseComObject(worksheet);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excelApp);
}
}
}
这样,你就可以在.NET Core 3.1中打开Excel文件,编辑并将其另存为流了。请注意,这个方法依赖于Microsoft Office Interop库,因此在运行代码之前,确保你的机器上已经安装了Microsoft Office。
领取专属 10元无门槛券
手把手带您无忧上云