How to Import and Export CSV Files Using WinForms C# and VB.NET
Tags: webdev, devops, dotnet, tutorial
Published: 2023-12-06 17:33:08

---
canonical_url: https://developer.mescius.com/blogs/how-to-import-and-export-csv-files-using-winforms-c-sharp-vb-net
description: Learn how to import and export CSV files using WinForms C# and VB.NET. See more from Spread.NET today.
---
This post describes importing and exporting your spreadsheets with CSV (Comma Separate Values) files directly in your .NET WinForms applications using the **Spread.NET** spreadsheet.

We will use the **Spread Designer** tool in run-time for editing Excel spreadsheet instances inside your running application with just one line of code. Finally, I will show how to create a simple front-end spreadsheet user interface that integrates the **FpSpread** spreadsheet control with the **NameBox** and **FormulaTextBox** controls using splitter panes to create the main user interface, as well as how to implement menu items to handle **File - Open, File - Save**, and **File - Design** commands in **C#** and **VB**.

Here are the steps for importing and exporting CSV files in C# and VB.net WinForms:

*   [<span>Create the Project</span>](#step1)
*   [<span>Configure the Project</span>](#step2)
*   [<span>Create the File Menu</span>](#step3)
*   [<span>Create SplitContainer1</span>](#step4)
*   [<span>Configure SplitContainer1</span>](#step5)
*   [<span>Create SplitContainer2</span>](#step6)
*   [<span>Create the FpSpread</span>](#step7)
*   [<span>Create the NameBox</span>](#step8)
*   [<span>Create the FormulaTextBox</span>](#step9)
*   [<span>Create the WinForms Spreadsheet Designer Component</span>](#step10)
*   [<span>Create Event Handlers for File Menu Items</span>](#step11)
*   [<span>Add Event Handler Code</span>](#step12)

These steps require:

*   **Microsoft Visual Studio 2022 (note: while these steps are for VS2022 and .NET 6, Spread.NET WinForms can also work in earlier versions of Visual Studio targeting .NET 4.6.2+, following these same steps)**
*   **Spread.NET for WinForms** (trial version or licensed) - **Get your free 30-day trial of Spread.NET** **WinForms **[**here**](https://developer.mescius.com/spreadnet/download "https://developer.mescius.com/spreadnet/download")**.**

## <a id="step1"></a>Step 1: Create the Project

![Create a New Project](//cdn.mescius.io/umb/media/twspij4g/createnewproject.png?rmode=max&width=765&height=434)

We can start by creating a new project in **Visual Studio 2022** by selecting **C#, Windows**, and **Desktop** to filter the projects and then selecting either **C#** or **VB** **WinForms App**.

## <a id="step2"></a>Step 2: Configure the Project

![Configure the Project](//cdn.mescius.io/umb/media/2f0kkfcr/configureproject.png?rmode=max&width=754&height=428)

Type **SpreadWinformsCSVIO** for **Project Name**.

## <a id="step3"></a>Step 3: Create the File Menu

Now, let’s add a **MenuStrip.** In the **Toolbox** window (**F4**), under the category for **Menus & Toolbars** and, double-click the **MenuStrip** component to create a new **MenuStrip** in the form:

![Menu Strip Toolbox](//cdn.mescius.io/umb/media/smfhfudo/menustriptoolbox.png)

Create the menu items for **File – Open**, **File – Save**, **File – Save As**, **File – Design**, and **File – Exit** by clicking using the associated shortcut keys:

![File Menu](//cdn.mescius.io/umb/media/mf4pb15p/filemenu.jpg) 

Note that the **File - Save** menu item should initially be disabled. The menu separators (use **"-"** for the menu item text to create a menu separator) and shortcut keys are optional but recommended. We will add code for those menu items in a later step.

## <a id="step4"></a>Step 4: Create SplitContainer1

**Note: **Adding splitters isn't strictly necessary to use FpSpread, but the SplitContainer control makes creating a friendly and flexible spreadsheet interface much easier because it automatically handles resizing for the spreadsheet, namebox, and formula text box controls without requiring any code.

In the **Toolbox** (**CTRL+ALT+X**), expand the category for **Containers**, then double-click the **SplitContainer** control to create **_splitContainer1_**_:_

_ ![Split Container Toolbox](//cdn.mescius.io/umb/media/k03njkhm/splitcontainertoolbox.png)_

_<span></span>_

## <a id="step5"></a>Step 5: Configure SplitContainer1

In the **Properties** window (**F4**), for **splitContainer1**, set **Orientation** to **Horizontal**, then set **Panel1MinSize** and **SplitterDistance** to **23**:

![SplitContainer 1 Properties](//cdn.mescius.io/umb/media/suqd2ly1/splitcontainer1properties.png)

The spreadsheet will be in the bottom pane, the formula bar interface will be in the top pane, and the splitter will determine the height of the **FormulaTextBox** control for showing long formulas that wrap to new lines.

## <a id="step6"></a>Step 6: Create SplitContainer2

In the **Toolbox** (**CTRL+ALT+X**), drag-and-drop a new **SplitContainer** inside the top pane (**Panel1**) of **splitContainer1** to create **splitContainer2**:

![SplitContainer 2](//cdn.mescius.io/umb/media/z1apfmje/07-splitcontainer2.png)

In the **Properties** window (**F4**), for **splitContainer2** set **Panel1MinSize** and **SplitterDistance** to **150**:

![SplitContainer2 Properties](//cdn.mescius.io/umb/media/5mldxpbn/splitcontainer2properties.png)

## <a id="step7"></a>Step 7: Create the FpSpread

In **Solution Explorer**, expand the **Solution SpreadNetQuickStart** and **Project SpreadNetQuickStart**, then right-click **Dependencies **and select **Manage NuGet Packages…** (or press **ALT+P+N+N+N+ENTER**):

![Manage NuGet Packages](//cdn.mescius.io/umb/media/ohqibs3e/managenugetpackages.png) 

Then, in **NuGet Package Manager**, select the **Browse** in the upper-left, then type **Spread.WinForms** in the search box to find the latest **GrapeCity.Spread.WinForms**, then click **Install**:

![NuGet Package Manager](//cdn.mescius.io/umb/media/y4kjjbqj/nugetpackagemanager.png?rmode=max&width=757&height=514)

After installing **GrapeCity.Spread.WinForms**, go ahead and also install **GrapeCity.Spread.WinForms.Design** – this package contains the **fpSpreadDesigner** component for showing the **Spread Designer** tool in runtime.

Then, in the **Toolbox** (**CTRL+ALT+X**), select the **FpSpread** control:

 ![FpSpread Toolbox](//cdn.mescius.io/umb/media/x1anaku3/fpspreadtoolbox.png)

Finally, draw an instance of **FpSpread** into the bottom pane (**Panel2**) of **SplitContainer1**. The **Spread Designer** tool may open when you create the control (that is the default behavior) – for now, close the **Spread Designer** if it appears. 

 ![FpSpread Form](//cdn.mescius.io/umb/media/as4nsfm0/fpspreadform.png?rmode=max&width=713&height=427)

Using the **Property Grid (F4)**, set the **Dock** property to **Fill:**

 ![FpSpread Dock](//cdn.mescius.io/umb/media/bmgen4pj/fpspreaddock.png)

## <a id="step8"></a>Step 8: Create the NameBox

In the **Toolbox** (**CTRL+ALT+X**), expand the category for **GrapeCity Spread for WinForms** and select the **NameBox** control:

![Namebox Toolbox](//cdn.mescius.io/umb/media/ucbnbxyv/nameboxtoolbox.png)

Draw a new **NameBox** inside the upper-left **Panel1** (**SplitContiner2.Panel1**):

![NameBox Form](//cdn.mescius.io/umb/media/njbprcwz/nameboxform.png?rmode=max&width=706&height=421)

In the **Properties** window (**F4**), for **nameBox1,** set **Dock** to **Fill**:

![NameBox Properties](//cdn.mescius.io/umb/media/oh4h5xty/nameboxproperties.png)

In the upper-right corner of **nameBox1**, click the indicator to open the **NameBox Tasks**, then click the **AttachTo** drop-down and select **fpSpread1** – this will generate code in the form code-behind to attach the **NameBox** control to the **FpSpread** control:

 ![NameBox Attachment](//cdn.mescius.io/umb/media/q3unguaw/nameboxattachment.png)

## <a id="step9"></a>Step 9: Create the FormulaTextBox

In the **Toolbox** (**CTRL+ALT+X**), expand **Containers** and select the **Panel** control:

![Panel Toolbox](//cdn.mescius.io/umb/media/3vkpvbcv/paneltoolbox.png) 

Inside **Panel2** (to the right of **NameBox1**), draw a new **Panel**:

![Panel 2 Form](//cdn.mescius.io/umb/media/bfakbjio/panel2form.png)

In the **Properties** window (**F4**), for **panel1,** set **BorderStyle** to **FixedSingle** and **Dock** to **Fill**:

![Panel 1 Properties](//cdn.mescius.io/umb/media/fkujw1bb/panel1properties.png)

In the **Toolbox (CTRL+ALT+X),** select the **FormulaTextBox** control:

![Formula TextBox Toolbox](//cdn.mescius.io/umb/media/uc0oxwdl/formulatextboxtoolbox.png)

Inside **panel1** (which is inside **splitContainer2.Panel2**), draw a new **FormulaTextBox** control:

![Formula TextBox Form](//cdn.mescius.io/umb/media/l2jledgh/formulatextboxform.png)

In the **Properties** window (**F4**) for **formulaTextBox1,** set **BorderStyle** to **None** and **Dock** to **Fill**:

![Formula TextBox Properties](//cdn.mescius.io/umb/media/4hqeg121/formulatextboxproperties.png)

In the upper-right corner of **formulaTextBox1**, click the indicator to open the **FormulaTextBox Tasks,** then click the **AttachTo** drop-down and select **fpSpread1** – this will generate code in the form code-behind to attach the **FormulaTextBox** control to the **FpSpread** control:

![Formula TextBox Attachment](//cdn.mescius.io/umb/media/mxjmvjd1/formulatextboxattach.png)

## <a id="step10"></a>Step 10: Create the WinForms Spreadsheet Designer Component

Now, in the **Toolbox** window (**CTRL+ALT+X**) under the category **GrapeCity Spread Design for WinForms,** double-click the **FpSpreadDesigner** component to create a new **FpSpreadDesigner** in the form:

![FpSpread Designer Toolbox](//cdn.mescius.io/umb/media/rkwbvpmp/fpspreaddesignertoolbox.png)

The **fpSpreadDesigner1** component just added should show in the form component tray next to the components **menuStrip1** and **fpSpread1_Sheet1**:

![FpSpread Designer Form](//cdn.mescius.io/umb/media/5r0lqs02/fpspreaddesignerformitem.png)

## <a id="step11"></a>Step 11: Create Event Handlers for File Menu Items

![File Menu Handlers Design](//cdn.mescius.io/umb/media/ia2jfbqr/filemenuhandlersdesign.png)

For each menu item in the **File** menu, double-click that menu item in the design view until each menu item has an associated menu handler generated in the VB or C# code:

![File Menu Handlers](//cdn.mescius.io/umb/media/qnkcoa2h/filemenuhandlers.png)

## <a id="step12"></a>Step 12: Add Event Handler Code

Copy the following code to implement the event handlers:

**[C#]**

**Add Event Handler Code C#**

```
    private string mFileName = null;

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
        ofd.FilterIndex = 0;
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            mFileName = ofd.FileName;
            fpSpread1.Sheets[0].LoadTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "");
            saveToolStripMenuItem.Enabled = true;
        }
    }

    private void saveToolStripMenuItem_Click(object sender, EventArgs e)
    {
        fpSpread1.Sheets[0].SaveTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "");
    }

    private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*";
        sfd.FilterIndex = 0;
        sfd.FileName = mFileName;
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            mFileName = sfd.FileName;
            fpSpread1.Sheets[0].SaveTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "");
            saveToolStripMenuItem.Enabled = true;
        }
    }

    private void designToolStripMenuItem_Click(object sender, EventArgs e)
    {
        fpSpreadDesigner1.ShowDialog(fpSpread1);
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DialogResult ret = MessageBox.Show("Do you want to save this file before closing?", "Save Spreadsheet", MessageBoxButtons.YesNoCancel);
        if (ret == DialogResult.Cancel)
            return;
        else if (ret == DialogResult.Yes)
            saveToolStripMenuItem_Click(null, EventArgs.Empty);
        Close();
    }

```
**[VB]**

**Add Event Handler Code VB**

```
    Private mFileName As String = Nothing

    Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
        Dim ofd As New OpenFileDialog
        ofd.Filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*"
        ofd.FilterIndex = 0
        If ofd.ShowDialog() = DialogResult.OK Then
            mFileName = ofd.FileName
            FpSpread1.Sheets(0).LoadTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "")
            SaveToolStripMenuItem.Enabled = True
        End If
    End Sub

    Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
        FpSpread1.Sheets(0).SaveTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "")
    End Sub

    Private Sub SaveAsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveAsToolStripMenuItem.Click
        Dim sfd As SaveFileDialog = New SaveFileDialog()
        sfd.Filter = "CSV file (*.csv)|*.csv| All Files (*.*)|*.*"
        sfd.FilterIndex = 0
        sfd.FileName = mFileName
        If sfd.ShowDialog() = DialogResult.OK Then
            mFileName = sfd.FileName
            FpSpread1.Sheets(0).SaveTextFile(mFileName, FarPoint.Win.Spread.TextFileFlags.None, FarPoint.Win.Spread.Model.IncludeHeaders.None, "", ",", "")
            SaveToolStripMenuItem.Enabled = True
        End If
    End Sub

    Private Sub DesignToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DesignToolStripMenuItem.Click
        FpSpreadDesigner1.ShowDialog(FpSpread1)
    End Sub

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
        Dim ret As DialogResult = MessageBox.Show("Do you want to save this file before closing?", "Closing", MessageBoxButtons.YesNoCancel)
        If ret = DialogResult.Cancel Then
            Return
        ElseIf ret = DialogResult.Yes Then
            SaveToolStripMenuItem_Click(Nothing, EventArgs.Empty)
        End If
        Close()
    End Sub
```

The code for **File - Open** uses the **OpenFileDialog** to browse for a CSV file, then uses the **FpSpread.Sheets.LoadTextFile** method to open the selected CSV file. The code for **File - Save** uses **FpSpread.Sheets.SaveTextFile** to save the spreadsheet data to a CSV, and the code for **File - Save As** uses the **SaveFileDialog** to allow the user to save the file to another location or use another name. This functionality allows for C# or VB.NET CSV file import and export.

The code in File-Design uses the **FpSpreadDesigner.ShowDialog** method to show the **Spread Designer** tool in run-time, make changes, and then apply those changes back to the spreadsheet instance in the form. Finally, the code in **File - Exit** prompts the user whether to save the file and then uses the **Close** method to close the form.

## Ready to Build and Run!

![Final Results](//cdn.mescius.io/umb/media/00qbyeil/finalresult.png?rmode=max&width=760&height=427)

The project is ready to build and run. The File-Design menu will open the **Spread Designer** tool in run-time, as shown above, which can apply changes to the spreadsheet instance running in the form. See how Spread .NET can give you the power to import and export your spreadsheets to CSV with C# or VB.NET within your application.

In another article series, we demonstrate [How to Import and Export Excel XLSX in WinForms C# and VB.NET](https://developer.mescius.com/blogs/how-to-import-export-excel-xlsx-in-c-sharp-vb-net).

[**Download the Sample.**](https://cdn.mescius.io/assets/developer/blogs/spread/20231107-how-to-import-and-export-csv-files-using-winforms-c-sharp-vb-net/SpreadWInformsCSVIO.zip)