在内存中阅读Excel电子表格

如何阅读刚刚发布到我的服务器的Excel电子表格? 我搜索了一些东西,但我只找到了如何阅读带有文件名路径的Excel电子表格,这不是我的情况。

我需要这样的东西:

public ActionResult Import(HttpPostedFileBase file) { var excel = new ExcelQueryFactory(file); //using linq to excel } 

遗憾的是,无法使用LinqToExcel从流中读取电子表格。

那是因为它使用OLEDB从电子表格中读取而无法从流中读取。

我遇到了同样的问题,但我不想改用付费服务,所以这就是我所做的。

 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 All(string sheetName = "") { if (string.IsNullOrEmpty(sheetName)) { sheetName = (typeof (T)).Name; } var excelSheet = new ExcelQueryFactory(_tempFilePath); return from t in excelSheet.Worksheet(sheetName) select t; } public void Dispose() { File.Delete(_tempFilePath); } } 

这是一个测试

 [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(); Assert.NotEmpty(products); } } } 

这是MemoryFile.cs。 此文件仅用于测试。 它只是HttpPostedFileBase的一个实现,因此您可以测试您的控制器和我的小助手。 这是从另一篇文章中借来的。

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

您可以使用HttpPostedFileBaseInputStream属性来读取内存中的Excel电子表格。

我使用ClosedXML nuget包来从流中读取excel内容,这在您的案例中是可用的。 它有一个简单的重载,它将流指向excel文件(也就是工作簿)的流。

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

 using ClosedXML.Excel; 

源代码:

 public ActionResult Import(HttpPostedFileBase file) { //HttpPostedFileBase directly is of no use so commented your code //var excel = new ExcelQueryFactory(file); //using linq to excel var stream = file.InputStream; 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); } } } 

您需要Office Interops程序集。 检查Excel对象模型以供参考。