Trying to read an Excel file with EPPlus works on

2020-07-08 07:00发布

问题:

When I published my project and ran it on the server, it worked. EPPlus found all 4 worksheets, iterated through them, and uploaded my data to SQL.

But when I run it through my browser, or my coworkers browser, it shows 0 worksheets.

Any idea why this might be happening? There's not much to the code at that point, but here's that part:

using (ExcelPackage package = new ExcelPackage(new FileInfo(strFile)))
{
    if (package.Workbook.Worksheets.Count <= 0)
        strError = "Your Excel file does not contain any work sheets";
    else
    {
        foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
        {

回答1:

EPPlus can load a file into memory. You're just not doing it that way. I think if you do this, you're less likely to run into trouble reading it from the file system. You can turn uploaded files into a byte array without having it as a file first, but in my example I'm opening an existing file. If you provide the code for how you're uploading the file, I can update my example.

byte[] file = File.ReadAllBytes(@"C:\file.xlsx");
using (MemoryStream ms = new MemoryStream(file))
using (ExcelPackage package = new ExcelPackage(ms))
{
    if (package.Workbook.Worksheets.Count == 0)
        strError = "Your Excel file does not contain any work sheets";
    else
    {
        foreach (ExcelWorksheet worksheet in package.Workbook.Worksheets)
        {