2009-02-18 65 views
13

我需要一種方法從流中讀取Excel文件。它似乎不適用於ADO.NET的做事方式。從流中讀取excel文件

這種情況是,用戶通過FileUpload上傳文件,我需要從文件中讀取一些值並導入到數據庫。

由於幾個原因我不能將文件保存到磁盤,並沒有理由這樣做。

那麼,誰知道從FileUpload流中讀取Excel文件的方法?

+0

看一看這個做方案http://stackoverflow.com/a/13978464/1242061 – escist 2013-03-20 12:36:53

回答

0

Infragistics有一個excel component可以從流中讀取excel文件。

我在這裏使用它在一個項目,它運作良好。

也可以很容易地修改開放源碼myXls component來支持這一點。 XlsDocument contstructor只支持從文件名給出的文件進行加載,但它通過創建FileStream並讀取Stream來工作,因此將其更改爲支持從流加載應該是微不足道的。

編輯: 我發現你找到了一個解決方案,但我只是想說明我更新了組件的源代碼,以便它現在可以直接從一個流中讀取一個excel文件。 :-)

12

看來我發現自己的問題靈魂。

http://www.codeplex.com/ExcelDataReader

這個庫似乎很好地工作,它需要一個流中讀取Excel文件。

ExcelDataReader reader = new ExcelDataReader(ExcelFileUpload.PostedFile.InputStream); 
+1

當前語法似乎爲: IExcelDataReader reader = new ExcelReaderFactory.CreateOpenXmlReader(ExcelFileUpload.PostedFile.InputStream); 或97-2003格式文件IExcelDataReader reader = new ExcelReaderFactory.CreateBinaryReader(ExcelFileUpload.PostedFile。InputStream的); – StuartQ 2014-07-22 15:03:30

4

SpreadsheetGear可以做到這一點:

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

您可以用free evaluation自己試試看。

聲明:我自己的SpreadsheetGear LLC

+2

+1我只是需要自己做這件事,很高興看到SSG可以做到這一點,因爲我已經有了它的許可證 - 節省我任何搞砸! – 2011-11-18 17:13:27

3

這可以很容易地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(); 
     } 
    } 
} 
0

我用ClosedXML nuget包從流中讀取excel內容。它在XLWorkbook類中有一個構造函數過載,它將流指向一個excel文件(aka工作簿)。

在你的代碼文件的頂部

導入的命名空間:

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); 
    } 
}