15

我需要一种从流中读取 Excel 文件的方法。它似乎不适用于 ADO.NET 的处理方式。

场景是用户通过 FileUpload 上传文件,我需要从文件中读取一些值并导入数据库。

由于多种原因,我无法将文件保存到磁盘,也没有理由这样做。

那么,有人知道从 FileUpload 流中读取 Excel 文件的方法吗?

4

5 回答 5

15

看来我自己找到了解决问题的方法。

http://www.codeplex.com/ExcelDataReader

这个库似乎工作得很好,它需要一个流来读取 excel 文件。

ExcelDataReader reader = new ExcelDataReader(ExcelFileUpload.PostedFile.InputStream);
于 2009-02-18T10:51:03.750 回答
5

这可以通过EPPlus轻松完成。

//the excel sheet as byte array (as example from a FileUpload Control)
byte[] bin = FileUpload1.FileBytes;

//gen the byte array into the memorystream
using (MemoryStream ms = new MemoryStream(bin))
using (ExcelPackage package = new ExcelPackage(ms))
{
    //get the first sheet from the excel file
    ExcelWorksheet sheet = package.Workbook.Worksheets[1];

    //loop all rows in the sheet
    for (int i = sheet.Dimension.Start.Row; i <= sheet.Dimension.End.Row; i++)
    {
        //loop all columns in a row
        for (int j = sheet.Dimension.Start.Column; j <= sheet.Dimension.End.Column; j++)
        {
            //do something with the current cell value
            string currentCellValue = sheet.Cells[i, j].Value.ToString();
        }
    }
}
于 2017-03-31T11:32:54.667 回答
4

SpreadsheetGear可以做到:

SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(stream);

您可以通过免费评估自己尝试。

免责声明:我拥有 SpreadsheetGear LLC

于 2009-02-18T20:40:45.313 回答
0

Infragistics有一个excel 组件,可以从流中读取 excel 文件。

我在这里的一个项目中使用它并且效果很好。

此外,可以轻松修改开源myXls 组件以支持此功能。XlsDocument 构造函数仅支持从由文件名给出的文件加载,但它通过创建 FileStream 然后读取 Stream 来工作,因此将其更改为支持从流加载应该是微不足道的。

编辑:我看到您找到了解决方案,但我只想指出我更新了组件的源代码,以便它现在可以直接从流中读取 excel 文件。:-)

于 2009-02-18T10:07:50.750 回答
0

我使用ClosedXML nuget 包从流中读取 excel 内容。它在类中有一个构造函数重载,XLWorkbook它将流指向一个 excel 文件(又名工作簿)。

在代码文件顶部导入的命名空间:

using ClosedXML.Excel;

源代码:

var stream = /*obtain the stream from your source*/;
if (stream.Length != 0)
{
    //handle the stream here
    using (XLWorkbook excelWorkbook = new XLWorkbook(stream))
    {
        var name = excelWorkbook.Worksheet(1).Name;
        //do more things whatever you like as you now have a handle to the entire workbook.
        var firstRow = excelWorkbook.Worksheet(1).Row(1);
    }
}
于 2017-11-30T10:53:20.983 回答