简体   繁体   English

Asp.net Core导入Excel文件FileNotFoundException

[英]Asp.net Core Import Excel File FileNotFoundException

I've had this working but it has stopped and I can't figure out why. 我已经进行了这项工作,但是它已经停止了,我不知道为什么。 I'm importing a simple excel file, using EPPlus.Core v1.3. 我正在使用EPPlus.Core v1.3导入一个简单的excel文件。 Here's the code I'm using: 这是我正在使用的代码:

public async Task<IActionResult> Import(IFormFile file)
    {
        //Get file
        var newfile = new FileInfo(file.FileName);
        var fileExtension = newfile.Extension;

        //Check if file is an Excel File
        if (fileExtension.Contains(".xls"))
        {
            //Create an excel package
            using (var package = new ExcelPackage(newfile))
            {
                //Get the first worksheet in the file
                var worksheet = package.Workbook.Worksheets[1];
...

The var worksheet line throws an error var工作表行抛出错误

"IndexOutOfRangeException: Worksheet position out of range." “ IndexOutOfRangeException:工作表位置超出范围。”

However, when I look at the package variable I see this error 但是,当我查看包变量时,会看到此错误

"Length = 'package.File.Length' threw an exception of type 'System.IO.FileNotFoundException'" “ Length ='package.File.Length'引发了'System.IO.FileNotFoundException'类型的异常”

What am I missing here? 我在这里想念什么? Like I said, this used to work and I can't think of anything I changed related to this code to cause this issue. 就像我说的那样,这曾经奏效,而且我想不出与该代码相关的任何更改来导致此问题。

Is it the same file also? 它也是同一个文件吗? It looks like the file might not have two worksheets and since the index is 1, it is looking for the second worksheet. 似乎该文件可能没有两个工作表,并且由于索引为1,因此它正在寻找第二个工作表。

You need to load the file in a MemoryStream and create a ExcelPackage from there. 您需要将文件加载到MemoryStream并从那里创建一个ExcelPackage

using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes))
using (ExcelPackage excelPackage = new ExcelPackage(ms))
{
    //work with the excel document
}

FileUpload1.FileBytes if for asp.net webforms, but I'm guessing Core has something similar. 如果是asp.net网络表单,则为FileUpload1.FileBytes ,但我猜想Core也有类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM