Stavo correndo il tuo stesso problema ma non volevo passare a un servizio a pagamento quindi questo è quello che ho fatto.
public class DataImportHelper : IDisposable
{
private readonly string _fileName;
private readonly string _tempFilePath;
public DataImportHelper(HttpPostedFileBase file, string tempFilePath)
{
_fileName = file.FileName;
_tempFilePath = Path.Combine(tempFilePath, _fileName);
(new FileInfo(_tempFilePath)).Directory.Create();
file.SaveAs(_tempFilePath);
}
public IQueryable<T> All<T>(string sheetName = "")
{
if (string.IsNullOrEmpty(sheetName))
{
sheetName = (typeof (T)).Name;
}
var excelSheet = new ExcelQueryFactory(_tempFilePath);
return from t in excelSheet.Worksheet<T>(sheetName)
select t;
}
public void Dispose()
{
File.Delete(_tempFilePath);
}
}
Ecco un test
[Fact]
public void AcceptsAMemoryStream()
{
MemoryFile file;
using (var f = File.OpenRead("SampleData.xlsx"))
{
file = new MemoryFile(f, "multipart/form-data", "SampleData.xlsx");
using (var importer = new DataImportHelper(file, "Temp/"))
{
var products = importer.All<Product>();
Assert.NotEmpty(products);
}
}
}
Ecco MemoryFile.cs. Questo file è usato solo per i test. È solo un'implementazione di HttpPostedFileBase in modo da poter testare i controller e il mio piccolo aiuto. Questo è stato preso in prestito da un altro post.
public class MemoryFile : HttpPostedFileBase
{
Stream stream;
string contentType;
string fileName;
public MemoryFile(Stream stream, string contentType, string fileName)
{
this.stream = stream;
this.contentType = contentType;
this.fileName = fileName;
}
public override int ContentLength
{
get { return (int)stream.Length; }
}
public override string ContentType
{
get { return contentType; }
}
public override string FileName
{
get { return fileName; }
}
public override Stream InputStream
{
get { return stream; }
}
public override void SaveAs(string filename)
{
using (var file = File.Open(filename, FileMode.Create))
stream.CopyTo(file);
}
}
fonte
2012-12-20 18:41:53
Possibile duplicato di questa domanda: [Leggi file da un flusso excel] (http: // StackOverflow .com/domande/560435/lettura-excel-file-da-un-stream)? –
Dovrai prendere in considerazione problemi come: Cosa succede se il tavolo non è sul primo foglio? Cosa succede se non è nell'intervallo specificato? Excel ha le abilità OleDb, ma devi usare metodi come 'GetOleDbSchema()' per ottenere le schede, quindi conoscere l'intervallo da interrogare. È possibile, ma non sono solo 3 righe di codice. –
@DominicZukiewicz Questo non è un problema reale nel mio caso perché ogni file di caricamento avrà lo stesso schema. – MuriloKunze