Easily Convert Excel File to CSV By Using C#

CSV (Comma Separated Values) is used to save data in plain-text form. Because of its simple format, data in CSV files can load to spreadsheet and database. Also, because it is widely recognized, some software applications support to import or export CSV.

In this post, I will introduce a method to convert Excel to CSV. The original Excel file I want to convert has several formats, such as font style, background color and so on. After converting, we can find that all the formats in original file are moved.

Original Excel File

The following steps show details to convert Excel to CSV by using C#.

Note: I use a C# .NET Excel component Spire.XLS for .NET in my example. Therefore, I have added its DLL file as reference in my project. The other references I add is system.text because CSV is plain text file.

  1. Load the file which I want to convert and initialize worksheets.
  2. Save this file to CSV.
  3. Launch this converted file.

Coding:

using Spire.Xls;
using System.Text;

namespace Xls2CSV
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load File and Initialize Worksheet
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@”D:\work\My Documents\Customer.xlsx”);
            Worksheet sheet = workbook.Worksheets[0];

            //Save File as CSV and Launch
            sheet.SaveToFile(“result.csv”,“,”,Encoding.UTF8);
            System.Diagnostics.Process.Start(“result.csv”);
        }
    }
}

RESULT:

DOWNLOAD Spire.XLS for .NET Here

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s