在 C# 控制台应用程序中从内存流读取 Excel 文件

问题描述 投票:0回答:3

我正在从 ftp 获取 Excel 文件并将该文件放入内存流中。我必须从内存流中读取该文件。我尝试通过 Excel Interop,但它不接受内存流作为

中的参数
xlWorkBook = xlApp.Workbooks.Open(strm, 0, true, 5, "", "", true, 
   Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

根据系统要求,我无法临时保存该文件;因为我正在使用 Azure Web 作业进行控制台应用程序部署。有什么方法可以从内存流中读取文件,或者我可以将该内存流转换为字符串数组吗?

c# excel azure console-application
3个回答
0
投票

此外 EasyXLS 接受流,包括 MemoryStream。 我不知道您是否只需要 Excel 单元格中的数据或其他信息,但下面的代码仅适用于数据:

ExcelDocument excelWorkbook = new ExcelDocument();
DataSet ds = excelWorkbook.easy_ReadXLSActiveSheet_AsDataSet(memoryStream);

有关阅读 Excel 的更多详细信息,您可以在以下位置找到: https://www.easyxls.com/manual/FAQ/read-excel-file-in-dot-net.html


0
投票

Azure Webjob 中不存在 MS Office,因此我们无法在 Azure Webjob 中使用 Microsoft.Office.Interop Dll。请尝试使用 DocumentFormat.OpenXml 来做到这一点。以下是来自官方文档的演示代码。我还找到了有关如何使用 Open XML SDK 读取和写入 Microsoft Excel 的另一个教程。

public static void OpenAndAddToSpreadsheetStream(Stream stream)
{
    // Open a SpreadsheetDocument based on a stream.
    SpreadsheetDocument spreadsheetDocument =
        SpreadsheetDocument.Open(stream, true);

    // Add a new worksheet.
    WorksheetPart newWorksheetPart = spreadsheetDocument.WorkbookPart.AddNewPart<WorksheetPart>();
    newWorksheetPart.Worksheet = new Worksheet(new SheetData());
    newWorksheetPart.Worksheet.Save();

    Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>();
    string relationshipId = spreadsheetDocument.WorkbookPart.GetIdOfPart(newWorksheetPart);

    // Get a unique ID for the new worksheet.
    uint sheetId = 1;
    if (sheets.Elements<Sheet>().Count() > 0)
    {
        sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
    }

    // Give the new worksheet a name.
    string sheetName = "Sheet" + sheetId;

    // Append the new worksheet and associate it with the workbook.
    Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
    sheets.Append(sheet);
    spreadsheetDocument.WorkbookPart.Workbook.Save();

    // Close the document handle.
    spreadsheetDocument.Close();

    // Caller must close the stream.
}

-1
投票

我建议您使用

ExcelDataReader 3.1.0
从 Excel 文件中读取数据。
现在您可以在
MemoryStream
中使用
ExcelReader
,如下所示:
请注意,旧 Excel 文件的阅读器 -
.xls
- 与新文件 -
.xlsx
- 不同。

var excelReader = originalFileName.EndsWith(".xls")
                ? ExcelReaderFactory.CreateBinaryReader(stream)
                : ExcelReaderFactory.CreateOpenXmlReader(stream);

如果您想从

string
中提取
MemoryStream
,您可以使用
StreamReader
:

var streamReader = new StreamReader(memoryStream);
var stringResult = streamReader.ReadToEnd();

如果您想处理

FileStream
,您可以将
MemoryStream
复制到其中,如下所示:

memoryStream.CopyTo(fileStream);
© www.soinside.com 2019 - 2024. All rights reserved.