[英]Read excel file from a stream
我需要一种从流中读取Excel文件的方法。 它似乎不适用于ADO.NET的处理方式。
方案是用户通过FileUpload上传文件,我需要从文件中读取一些值并导入到数据库。
由于多种原因,我无法将文件保存到磁盘,也没有理由这样做。
那么,有谁知道从FileUpload流中读取Excel文件的方法?
似乎我自己找到了这个问题的灵魂。
http://www.codeplex.com/ExcelDataReader
这个库似乎很好用,它需要一个流来读取excel文件。
ExcelDataReader reader = new ExcelDataReader(ExcelFileUpload.PostedFile.InputStream);
//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();
}
}
}
SpreadsheetGear可以做到:
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(stream);
您可以通过免费评估自行尝试。
免责声明:我拥有SpreadsheetGear LLC
我使用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);
}
}
Infragistics有一个excel组件 ,可以从流中读取excel文件。
我在这里的项目中使用它并且运行良好。
此外,可以轻松修改开源myXls组件以支持此功能。 XlsDocument contstructor仅支持从文件名给出的文件加载,但它通过创建FileStream然后读取Stream来工作,因此更改它以支持从流加载应该是微不足道的。
编辑:我看到你找到了一个解决方案但我只想注意我更新了组件的源代码,以便它现在可以直接从流中读取excel文件。 :-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.