How to load a XLSX document using C# and .NET

Step-by-step guide:

  1. Add SautinSoft.Excel from Nuget.
  2. Load a XLSX document from file or stream.

Полный код

using System;
using System.IO;
using SautinSoft.Excel;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free key here:   
            // https://sautinsoft.com/start-for-free/

            LoadXlsxFromFile();
            //LoadXlsxFromStream();
        }

        /// <summary>
        /// Loads a XLSX document into ExcelDocument from a file.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-xlsx-document-net-csharp-vb.php
        /// </remarks>
        static void LoadXlsxFromFile()
        {
            string filePath = @"..\..\..\example.xlsx";
            // The file format is detected automatically from the file extension: ".xlsx".
            ExcelDocument excel = ExcelDocument.Load(filePath);

            if (excel != null)
                Console.WriteLine("Loaded successfully!");

            Console.ReadKey();
        }

        /// <summary>
        /// Loads a XLSX document into ExcelDocument from a MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-xlsx-document-net-csharp-vb.php
        /// </remarks>
        static void LoadXlsxFromStream()
        {
            // Assume that we already have a XLSX document as bytes array.
            byte[] fileBytes = File.ReadAllBytes(@"..\..\..\example.xlsx");

            ExcelDocument dc = null;

            // Create a MemoryStream
            using (MemoryStream ms = new MemoryStream(fileBytes))
            {
                // Load a document from the MemoryStream.
                // Specifying LoadOptions we explicitly set that a loadable document is .xlsx.
                dc = ExcelDocument.Load(ms, new LoadOptions() { Format = FileFormat.Xlsx});
            }
            if (dc != null)
                Console.WriteLine("Loaded successfully!");

            Console.ReadKey();
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Excel

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Get your free key here:   
			' https://sautinsoft.com/start-for-free/

			LoadXlsxFromFile()
			'LoadXlsxFromStream();
		End Sub

		''' <summary>
		''' Loads a XLSX document into ExcelDocument from a file.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-xlsx-document-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub LoadXlsxFromFile()
			Dim filePath As String = "..\..\..\example.xlsx"
			' The file format is detected automatically from the file extension: ".xlsx".
			Dim excel As ExcelDocument = ExcelDocument.Load(filePath)

			If excel IsNot Nothing Then
				Console.WriteLine("Loaded successfully!")
			End If

			Console.ReadKey()
		End Sub

		''' <summary>
		''' Loads a XLSX document into ExcelDocument from a MemoryStream.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-xlsx-document-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub LoadXlsxFromStream()
			' Assume that we already have a XLSX document as bytes array.
			Dim fileBytes() As Byte = File.ReadAllBytes("..\..\..\example.xlsx")

			Dim dc As ExcelDocument = Nothing

			' Create a MemoryStream
			Using ms As New MemoryStream(fileBytes)
				' Load a document from the MemoryStream.
				' Specifying LoadOptions we explicitly set that a loadable document is .xlsx.
				dc = ExcelDocument.Load(ms, New LoadOptions() With {.Format = FileFormat.Xlsx})
			End Using
			If dc IsNot Nothing Then
				Console.WriteLine("Loaded successfully!")
			End If

			Console.ReadKey()
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.