在内存中阅读Excel电子表格

Mur*_*nze 14 c# linq-to-excel

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

我需要这样的东西:

public ActionResult Import(HttpPostedFileBase file)
{
     var excel = new ExcelQueryFactory(file); //using linq to excel
}
Run Code Online (Sandbox Code Playgroud)

Bre*_*red 20

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

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

}
Run Code Online (Sandbox Code Playgroud)

这是一个测试

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

            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Pau*_*aul 13

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

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