2017-08-12 189 views
0

我正在从ftp中获取Excel文件并在内存流中获取该文件。我必须从内存流中读取该文件。我到Excel互操作尝试,但它不接受内存流作为参数在在C#控制台应用程序中从内存流中读取Excel文件

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

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

+1

如果您使用的是Office互操作库,则无法将Excel文件加载到Stream中。实际上,您可能不应该在Azure上使用该库。还有其他的图书馆会为你做这个。 – DavidG

+0

@DavidG可以给我建议其他图书馆,将帮助完整。 –

回答

0

我建议您使用ExcelDataReader 3.1.0从Excel文件读取数据。
现在你可以使用MemoryStreamExcelReader这样的:
注意的旧Excel文件阅读器 - .xls - 是不同的形式较新的文件 - .xlsx - 。

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

如果你想提取从一个stringMemoryStream你可以使用一个StreamReader

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

如果你想工作在FileStream您可以MemoryStream复制到它是这样的:

memoryStream.CopyTo(fileStream); 
0

另外EasyXLS接受流,包括MemoryStream。 我不知道,如果你需要从Excel,或其他信息,仅细胞的数据,但代码波纹管是仅用于数据:

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

更多细节关于阅读擅长,你可以找到在这个位置: 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来做到这一点。以下是official document的演示代码。我还找到关于如何Read and Write Microsoft Excel with Open XML SDK的另一个教程。

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. 
} 
相关问题