Aspose.Cells使用教程:使用 C# 将 Excel 文件导出到流

在各种情况下,您可能需要将 Excel XLSX/XLS 文件导出或保存到内存流。对于这种情况,本文介绍了如何使用 C# 将 Excel 文件动态导出到 FileStream 对象。此外,您将学习如何从流加载 Excel 文件。

将 Excel 文件导出到流的 C# API

为了将 Excel 文件导出到流,我们将使用Aspose.Cells for .NET。它是一个功能丰富的 API,可让您创建和操作 Excel 文件。可以在慧都官网下载Aspose.Cells for .Net最新版

将 Excel 文件导出到 C# 中的 Stream

以下是使用 C# 将 Excel 文件导出到流的步骤。

  • 使用Workbook类加载 Excel 文件。
  • 创建一个新的FileStream对象。
  • 使用Workbook.Save(FileStream, SaveFormat)方法将 Excel 文件导出到流。

以下代码示例展示了如何将 Excel XLSX 文件导出到 FileStream 对象。

// Load your source workbook
Workbook workbook = new Workbook("excel.xlsx");

// Create a file stream for Excel file
FileStream stream = new FileStream("output.xlsx", FileMode.CreateNew);

// Export Excel file to stream
workbook.Save(stream, new XlsSaveOptions(SaveFormat.Xlsx));

// Perform operations on stream

// Close the stream
stream.Close();

从流加载 Excel 文件

Aspose.Cells for .NET 还允许您从流中加载 Excel 文件。以下是实现此目的的步骤。

  • 创建一个新的FileStream对象并将 Excel 文件加载到其中。
  • 创建一个新的Workbook对象并使用FileStream对象对其进行初始化。
  • 使用Workbook对象对 Excel 文件执行所需的操作。

以下代码示例显示了如何从 FileStream 加载 Excel 文件。

// Create a Stream object
FileStream fstream = new FileStream("Book2.xls", FileMode.Open);

// Create a Workbook object and open Excel file from stream
Workbook workbook = new Workbook(fstream);

// Manipulate Excel file
Console.WriteLine("Workbook opened using stream successfully!");

// Close stream
fstream.Close();

猜你喜欢

转载自blog.csdn.net/Augenstern__zyx/article/details/121033307