Aprire file Excel a livello di codice nelle applicazioni C# è un requisito comune, ma molti sviluppatori si scontrano con i limiti degli approcci tradizionali. In questa guida, vi mostreremo come aprire file Excel in C# utilizzando Openize.OpenXML SDK, una libreria gratuita e open source che non richiede l’installazione di Microsoft Excel.

Come aprire i file Excel in C# senza installare Excel

Il problema con i metodi tradizionali

La maggior parte degli sviluppatori inizia con Microsoft.Office.Interop.Excel, ma questo approccio presenta gravi limitazioni:

  • ❌ Richiede l’installazione di Excel su ogni macchina
  • ❌ Scarse prestazioni e perdite di memoria
  • ❌ Non adatto per applicazioni server
  • ❌ Problemi di threading nelle applicazioni web
  • ❌ Costi di licenza elevati

Soluzione: Openize.OpenXML SDK

L’Openize.OpenXML SDK risolve questi problemi:

  • ✅ Non è richiesta l’installazione di Excel
  • ✅ Alte prestazioni e filettatura sicura
  • ✅ Perfetto per applicazioni web e server
  • ✅ Open source e completamente gratuito
  • ✅ API semplice e intuitiva

Installazione

Aggiungi l’SDK Openize.OpenXML al tuo progetto:

<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />

Esempio base: aprire e leggere un file Excel

using Openize.Cells;
using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // Open existing Excel file
            using (var workbook = new Workbook("sample.xlsx"))
            {
                // Get the first worksheet
                var worksheet = workbook.Worksheets[0];
                
                Console.WriteLine($"Worksheet Name: {worksheet.Name}");
                Console.WriteLine($"Total Rows: {worksheet.GetRowCount()}");
                Console.WriteLine($"Total Columns: {worksheet.GetColumnCount()}");
                
                // Read specific cell values
                string cellA1 = worksheet.Cells["A1"].GetValue();
                string cellB1 = worksheet.Cells["B1"].GetValue();
                
                Console.WriteLine($"Cell A1: {cellA1}");
                Console.WriteLine($"Cell B1: {cellB1}");
            }
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Excel file not found!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }
}

Controlla se il file Excel esiste prima di aprirlo

using Openize.Cells;
using System.IO;

public class ExcelFileHandler
{
    public static void OpenExcelSafely(string filePath)
    {
        // Check if file exists
        if (!File.Exists(filePath))
        {
            Console.WriteLine($"File not found: {filePath}");
            return;
        }
        
        try
        {
            using (var workbook = new Workbook(filePath))
            {
                var worksheet = workbook.Worksheets[0];
                Console.WriteLine($"Successfully opened: {filePath}");
                Console.WriteLine($"First cell value: {worksheet.Cells["A1"].GetValue()}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Failed to open Excel file: {ex.Message}");
        }
    }
}

Leggi più fogli di lavoro

using Openize.Cells;

public class MultiSheetReader
{
    public static void ReadAllWorksheets(string filePath)
    {
        using (var workbook = new Workbook(filePath))
        {
            Console.WriteLine($"Total worksheets: {workbook.Worksheets.Count}");
            
            foreach (var worksheet in workbook.Worksheets)
            {
                Console.WriteLine($"\nWorksheet: {worksheet.Name}");
                Console.WriteLine($"Rows: {worksheet.GetRowCount()}");
                Console.WriteLine($"Columns: {worksheet.GetColumnCount()}");
                
                // Read first few cells
                for (int row = 1; row <= 3; row++)
                {
                    for (int col = 1; col <= 3; col++)
                    {
                        string cellRef = GetCellReference(row, col);
                        string value = worksheet.Cells[cellRef].GetValue();
                        Console.Write($"{value}\t");
                    }
                    Console.WriteLine();
                }
            }
        }
    }
    
    static string GetCellReference(int row, int col)
    {
        return $"{GetColumnLetter(col)}{row}";
    }
    
    static string GetColumnLetter(int columnNumber)
    {
        string columnLetter = string.Empty;
        while (columnNumber > 0)
        {
            columnNumber--;
            columnLetter = (char)('A' + columnNumber % 26) + columnLetter;
            columnNumber /= 26;
        }
        return columnLetter;
    }
}

Conclusion

L’SDK Openize.OpenXML offre un modo affidabile ed efficiente per aprire file Excel in C# senza le complicazioni di Excel Interop. È perfetto per applicazioni desktop, servizi web ed elaborazione lato server. Vantaggi principali:

  • Non è richiesta l’installazione di Excel
  • Alte prestazioni
  • Thread-safe per le applicazioni web
  • Open source e gratuito
  • API facile da usare Provalo nel tuo prossimo progetto e scopri la differenza!