how to create CSV string from DataTable in VB.NET or C#? | C# datatable export to csv with column name


how to create CSV string from DataTable in VB.NET or C#? | C# datatable export to csv with column name

VB.Net

Imports System.IO
Imports System.Data

        'Insert column name Start
Private sub CSV(byval Datatable)
        dim dt as datatable=nothing
        Dim n = 0
        Dim sb As StringBuilder = New StringBuilder
        'Header
        For Each column As DataColumn In dt.Columns
            If n = 0 Then
                sb.Append((WriteCSV(column.ColumnName.ToString)))
            Else
                sb.Append(("," + WriteCSV(column.ColumnName.ToString)))
            End If
            n += 1
        Next
        sb.AppendLine()
        For Each dr As DataRow In dt.Rows
            For Each dc As DataColumn In dt.Columns
                sb.Append((WriteCSV(dr(dc.ColumnName).ToString) + ","))
            Next
            sb.Remove((sb.Length - 1), 1)
            sb.AppendLine()
        Next

        Dim fileName As String = ShowSaveFileDialog("CSV Document", "comma-separated values|*.Csv")
        If fileName <> "" Then
            File.WriteAllText(fileName, sb.ToString)
            OpenFile(fileName)
        End If
  End If

  Private Function ShowSaveFileDialog(ByVal title As String, ByVal filter As String) As String
        Dim dlg As SaveFileDialog = New SaveFileDialog()
        Dim name As String = Replace(rgGSTType.Properties.Items(rgGSTType.SelectedIndex).ToString, ".", "_")
        name = Replace(name, " ", "_")
        name = Replace(name, "/", "_")

        Dim n As Integer = name.LastIndexOf(".") + 1
        If n > 0 Then
            name = name.Substring(n, name.Length - n)
        End If
        dlg.Title = "Export To " + title
        If Platform = "WIN PLATFORM" Then
            If ExcelfilePath = "" Then
                dlg.InitialDirectory = "C:\"
            Else
                dlg.InitialDirectory = ExcelfilePath
            End If
        Else
            If ExcelfilePath = "" Then
                dlg.InitialDirectory = "z:\home"
            Else
                dlg.InitialDirectory = ExcelfilePath
            End If
        End If
        dlg.FileName = name
        dlg.Filter = filter
        If dlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ExcelfilePath = ""
            Dim path() As String = dlg.FileName.Split("\")
            For i As Integer = 0 To path.Length - 2
                ExcelfilePath = ExcelfilePath & path(i) & "\"
            Next
            Return dlg.FileName
        End If
        Return ""
    End Function

    Private Sub OpenFile(ByVal fileName As String)
        If MessageBox.Show("Do you want to open this file?", "Export To...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            Try
                Dim process As System.Diagnostics.Process = New System.Diagnostics.Process()
                process.StartInfo.FileName = fileName
                process.StartInfo.Verb = "Open"
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
                process.Start()
            Catch

                MessageBox.Show(Me, "Cannot find an application on your system suitable for openning the file with exported data.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End Sub

C# .NET
using System.IO;
using System.Data;

    // Insert Column name Start
    private void CSV(void Datatable) {
        datatable dt = null;
        object n = 0;
        StringBuilder sb = new StringBuilder();
        // Header
        foreach (DataColumn column in dt.Columns) {
            if ((n == 0)) {
                sb.Append(WriteCSV(column.ColumnName.ToString));
            }
            else {
                sb.Append(("," + WriteCSV(column.ColumnName.ToString)));
            }
            
            n++;
        }
        
        sb.AppendLine();
        foreach (DataRow dr in dt.Rows) {
            foreach (DataColumn dc in dt.Columns) {
                               sb.Append((WriteCSV(dr[dc.ColumnName].ToString) + ","));
            }
            
            sb.Remove((sb.Length - 1), 1);
            sb.AppendLine();
        }
        
        string fileName = ShowSaveFileDialog("CSV Document", "comma-separated values|*.Csv");
        if ((fileName != "")) {
            File.WriteAllText(fileName, sb.ToString);
            OpenFile(fileName);
        }
        
    }
    
    private string ShowSaveFileDialog(string title, string filter) {
        SaveFileDialog dlg = new SaveFileDialog();
        string name = rgGSTType.Properties.Items(rgGSTType.SelectedIndex).ToString.Replace(".", "_");
        name = name.Replace(" ", "_");
        name = name.Replace("/", "_");
        int n = (name.LastIndexOf(".") + 1);
        if ((n > 0)) {
            name = name.Substring(n, (name.Length - n));
        }
        
        dlg.Title = ("Export To " + title);
        if ((Platform == "WIN PLATFORM")) {
            if ((ExcelfilePath == "")) {
                dlg.InitialDirectory = "C:\\";
            }
            else {
                dlg.InitialDirectory = ExcelfilePath;
            }
            
        }
        else if ((ExcelfilePath == "")) {
            dlg.InitialDirectory = "z:\\home";
        }
        else {
            dlg.InitialDirectory = ExcelfilePath;
        }
        
        dlg.FileName = name;
        dlg.Filter = filter;
        if ((dlg.ShowDialog() == Windows.Forms.DialogResult.OK)) {
            ExcelfilePath = "";
            string[] path = dlg.FileName.Split("\\");
            for (int i = 0; (i 
                        <= (path.Length - 2)); i++) {
                ExcelfilePath = (ExcelfilePath 
                            + (path[i] + "\\"));
            }
            
            return dlg.FileName;
        }
        
        return "";
    }
    
    private void OpenFile(string fileName) {
        if ((MessageBox.Show("Do you want to open this file?", "Export To...", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == Windows.Forms.DialogResult.Yes)) {
            try {
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.FileName = fileName;
                process.StartInfo.Verb = "Open";
                process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                process.Start();
            }
            catch (System.Exception MessageBox.Show) {
                this;
                "Cannot find an application on your system suitable for openning the file with exported data.";
                Application.ProductName;
                MessageBoxButtons.OK;
                MessageBoxIcon.Error;
            }
            
        }
        
    }

Post a Comment

0 Comments