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

Step-by-step guide:

  1. Add SautinSoft.Excel from Nuget.
  2. Load a CSV 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/

            LoadCsvFromFile();
            //LoadCsvFromStream();
        }

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

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

            Console.ReadKey();
        }

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

            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 .csv.
                dc = ExcelDocument.Load(ms, new LoadOptions() { Format = FileFormat.Csv });
            }
            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/

			LoadCsvFromFile()
			'LoadCsvFromStream();
		End Sub

		''' <summary>
		''' Loads a CSV document into ExcelDocument from a file.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-csv-document-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub LoadCsvFromFile()
			Dim filePath As String = "..\..\..\example.csv"
			' The file format is detected automatically from the file extension: ".csv".
			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 CSV document into ExcelDocument from a MemoryStream.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/excel/help/net/developer-guide/load-csv-document-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub LoadCsvFromStream()
			' Assume that we already have a CSV document as bytes array.
			Dim fileBytes() As Byte = File.ReadAllBytes("..\..\..\example.csv")

			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 .csv.
				dc = ExcelDocument.Load(ms, New LoadOptions() With {.Format = FileFormat.Csv})
			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. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.