使用ExcelPackage导入XLSX文件会引发错误.NET CORE

时间:2019-04-04 09:03:20

标签: c# asp.net-core asp.net-core-mvc excelpackage

我有一个jQuery,使用data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8将表导出为xlsx文件。当我要导入(更新)该文件时,我是通过此功能完成的

public static Dictionary<string, string> GetTableFromData(string data, string root)
    {
        if (string.IsNullOrEmpty(data))
        {
            return null;
        }
        var myString = data.Split(new char[] { ',' });
        byte[] bytes = Convert.FromBase64String(myString[1]);
        string fileName = Guid.NewGuid().ToString() + ".xlsx";
        string path = Path.Combine(root, "excel", fileName);
        using (Stream file = File.Create(path))
        {
            file.Write(bytes, 0, bytes.Length);
        }
        FileInfo fileInfo = new FileInfo(path);

        using (ExcelPackage package = new ExcelPackage(fileInfo))
        {
            ExcelWorksheet workSheet = package.Workbook.Worksheets[$"{fileName}"];
            int totalRows = workSheet.Dimension.Rows;

            Dictionary<string, string> languageDictionaries = new Dictionary<string, string>();

            for (int i = 1; i <= totalRows; i++)
            {
                languageDictionaries.Add(workSheet.Cells[i, 1].Value.ToString(), workSheet.Cells[i, 2].Value.ToString());
            }

            return languageDictionaries;
        }
    }

ExcelPackage总是让我出错,并说'The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor

然后我尝试在excel中制作一些测试xlsx文件,然后在导入该测试文件时实例化package。我尝试了其他解决方案,但无法找出导致此问题的原因。

1 个答案:

答案 0 :(得分:2)

您可以将HTML放入文件中并为其提供XLSX扩展名,Excel可以尽力将其呈现为电子表格,但这并不能使该文件成为有效的XLSX文件。

如果要以编程方式读取Excel文件,请确保它是有效的Excel文件。