-1

I have jquery where I export my table as xlsx file, using data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8. When I want to import that file (updated) I am doing it by this function

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

And ExcelPackage always throws me and error saying 'The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor

And I tried making some test xlsx file in excel and when I import that test file, package is instantiated. I tried other solutions and can't figure out what is causing this problem.

Ankit Mori
  • 705
  • 14
  • 23
Serlok
  • 432
  • 1
  • 10
  • 24
  • Does it also fail with smaller tables like few cells only? I ask in order to exclude the possibility of invalid values in the .xlsx file. – Prolog Apr 04 '19 at 09:19
  • @Prolog I think problem is in fact that xls can read HTML, but xlsx can't do that, and I generate on front that file, so probably it's failing when it is parsed. – Serlok Apr 04 '19 at 09:23
  • The code in your method doesn’t appear to be creating a valid XLSX file, which is why you’re being told it’s not a valid file. – Rob Apr 04 '19 at 09:26

1 Answers1

2

You can put HTML in a file and give it an XLSX extension, and Excel can do its best to render that as a spreadsheet, but that doesn't make that file a valid XLSX file.

If you want to programmatically read an Excel file, then make sure it's a valid Excel file.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272