Import CSV Files to Excel, PDF, DataGridView in C#

Files with the .csv extension are very similar to plain text files. CSV files are commonly used to transfer data from one database or spreadsheet format to another. This post gives examples of how to import data from CSV files into Excel worksheet, PDF form and DataGridView, by using .NET Excel component with C#.

CVS to Excel


//create a Workbook object
Workbook wb = new Workbook();

//load sample csv file
wb.LoadFromFile("SampleCSVFile.csv",",",1,1);

//save as excel file
wb.SaveToFile("toExcel.xlsx", ExcelVersion.Version2013);

2017-11-15_113237

CVS to PDF


//create a Workbook object
Workbook wb = new Workbook();

//load sample csv file
wb.LoadFromFile("SampleCSVFile.csv",",",1,1);

//render content of a worksheet into a single PDF page
wb.ConverterSetting.SheetFitToPage = true;

//autofit a column if the characters in the column exceed column width
Worksheet sheet = wb.Worksheets[0];
for (int i = 1; i < sheet.Columns.Length; i++)
{
    sheet.AutoFitColumn(i);
}

//save to PDF file
sheet.SaveToPdf("toPDF.pdf");

2017-11-15_113308

CVS to DataGridView


private void btnImport_Click(object sender, EventArgs e)
{
    //create a OpenFileDialog instance
    OpenFileDialog dialog = new OpenFileDialog();
    
    //set filter
    dialog.Filter = "CSV document(*.csv)|*.csv";

    //show dialog
    DialogResult result = dialog.ShowDialog();
    if (result == DialogResult.OK)
    {
        //get cvs file name
        string csvFile = dialog.FileName;

        //load csv to Wordbook instance
        Workbook wb = new Workbook();
        wb.LoadFromFile(csvFile,",");

        //export to datatable
        System.Data.DataTable datatable = wb.Worksheets[0].ExportDataTable();

        //display data in datagridview
        this.dataGridView1.DataSource = datatable;
    }
}

2017-11-15_113120

Advertisements

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