th3g3ntl3man
th3g3ntl3man

Reputation: 2106

Exception when I try to open an Excel file

When I try to open an excel file to count her sheet number, I get a System.DllNotFoundException. The dll in question is the ole32.dll. Online I read that this dll is relative of windows, but I work with Visual Studio Comunity for MacOS. How I can resolve this problem?

This is the code:

using System;
using System.IO;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

namespace Itec
{
    class MainClass
    {
        public static int countSheet(string file){

            int numSheet = 1;

            Application excelApp = new Application();
            Workbook workBook = excelApp.Workbooks.Open("d:/Book1.xls");

            numSheet = workBook.Sheets.Count;

            return numSheet;
        }

        public static void Main(string[] args)
        {
            string user, fileName, pathFile, ext;

            do
            {
                user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                Console.WriteLine("Inserire il nome del file (se è in una cartella scrivere nel seguente formato \"nomeCartella/nomeFile.pdf\"): ");
                fileName = Console.ReadLine();
                pathFile = "/Users/" + user + "/Desktop/" + fileName;
                ext      = Path.GetExtension(pathFile);

                if (String.Equals(ext, ".xlsx"))
                {
                    if (File.Exists(pathFile))
                    {
                        countSheet(pathFile);
                    }
                    else
                    {
                        Console.WriteLine("Il file inserito non esiste");
                        Console.WriteLine("Premere invio per riprovare");
                        Console.ReadKey();
                    }
                }
                else
                {
                    Console.WriteLine("Estensione non corretta");
                    Console.WriteLine("Premere invio per riprovare");
                    Console.ReadKey();
                }

            }
            while (!String.Equals(ext, ".xlsx") && !File.Exists(pathFile)); 
        }
    }
}

Upvotes: 1

Views: 631

Answers (1)

Chawin
Chawin

Reputation: 1466

Unfortunately Microsoft.Office.Interop.Excel won't work on Mac or Linux, as stated in this Github issue:

We have no plans to make Office COM APIs work on Mac or Linux. If the Office team produces docs on how to do this, we'd be happy to take a look. Closing as a result.

As an alternative I would recommened using EPPlus.

Upvotes: 1

Related Questions