Export Data from Tables to CSV with C# and .NET

Exporting data from tables to CSV files (comma-separated values) is a common requirement in many applications. CSV files are widely used for data exchange between different systems and platforms due to their simplicity and ease of use.

Let's look at a code example of how to export tabular data to CSV files using C# and .NET, using the capabilities of the SautinSoft PDF.Net Library:

  1. Add SautinSoft.PDF from NuGet.
  2. Load a document.
  3. Find tables.
  4. Get content data from tables to CSV string.
  5. Save the document in format csv.

Input file:

Output result:

Полный код

using System;
using System.IO;
using System.Text.RegularExpressions;
using SautinSoft;
using SautinSoft.Pdf;
using SautinSoft.Pdf.Content;

namespace Sample
{
    class Sample
    {
        static void Main(string[] args)
        {
            /// <summary>
            /// Find Tables.
            /// </summary>
            /// <remarks>
            /// Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/export-data-from-table-to-csv.php
            /// </remarks>
            // Before starting this example, please get a free 100-day trial key:
            // https://sautinsoft.com/start-for-free/

            // Apply the key here:
            // PdfDocument.SetLicense("...");

            string pdfFile = Path.GetFullPath(@"..\..\..\Item.pdf");
            string csv = "";

            using (var document = PdfDocument.Load(pdfFile))
            {
                // Find Tables.
                var tables = document.Pages[0].Content.FindTables();
                int col = -1;
                double sum = 0;

                // Get text from tables to CSV string.
                foreach (var table in tables) 
                {
                    foreach (var row in table.Rows) 
                    {
                        for (int i = 0; i < row.Cells.Count; i++)
                        {
                            if (col > -1 && i == col)
                            {
                                sum += Convert.ToDouble(row.Cells[i].ToString());
                            }
                            if (row.Cells[i].ToString().Contains("Total Price"))
                            {
                                col = i;
                            }
                            csv += row.Cells[i].ToString() + ';';
                        }
                        csv += "\n";
                    }
                    csv += "Total;;;" + sum.ToString();
                    sum = 0;
                    col = -1;
                    csv += "\n";
                }
            }

            var stream = new FileStream("Output.csv", FileMode.Create);
            stream.Close();
            File.WriteAllText("Output.csv", csv);

            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("Output.csv") { UseShellExecute = true });
        }
    }
}

Download

Option Infer On

Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Imports SautinSoft
Imports SautinSoft.Pdf
Imports SautinSoft.Pdf.Content

Namespace Sample
	Friend Class Sample
		Shared Sub Main(ByVal args() As String)
			''' <summary>
			''' Find Tables.
			''' </summary>
			''' <remarks>
			''' Details: https://sautinsoft.com/products/pdf/help/net/developer-guide/export-data-from-table-to-csv.php
			''' </remarks>
			' Before starting this example, please get a free 100-day trial key:
			' https://sautinsoft.com/start-for-free/

			' Apply the key here:
			' PdfDocument.SetLicense("...");

			Dim pdfFile As String = Path.GetFullPath("..\..\..\Item.pdf")
			Dim csv As String = ""

			Using document = PdfDocument.Load(pdfFile)
				' Find Tables.
				Dim tables = document.Pages(0).Content.FindTables()
				Dim col As Integer = -1
				Dim sum As Double = 0

				' Get text from tables to CSV string.
				For Each table In tables
					For Each row In table.Rows
						For i As Integer = 0 To row.Cells.Count - 1
							If col > -1 AndAlso i = col Then
								sum += Convert.ToDouble(row.Cells(i).ToString())
							End If
							If row.Cells(i).ToString().Contains("Total Price") Then
								col = i
							End If
							csv &= row.Cells(i).ToString() & ";"c
						Next i
						csv &= vbLf
					Next row
					csv &= "Total;;;" & sum.ToString()
					sum = 0
					col = -1
					csv &= vbLf
				Next table
			End Using

			Dim stream = New FileStream("Output.csv", FileMode.Create)
			stream.Close()
			File.WriteAllText("Output.csv", csv)

			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo("Output.csv") With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


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



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

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