Click here to Skip to main content
15,881,248 members
Articles / Productivity Apps and Services / Microsoft Office / Microsoft Excel
Tip/Trick

Import a CSV File Into an Excel Workbook Programmatically

Rate me:
Please Sign up or sign in to vote.
4.38/5 (7 votes)
19 Dec 2010CPOL3 min read 83.6K   12   8
Code to call Excel Interop to take a Comma-Separated-Values (.CSV) file and suck it into your Excel workbook programmatically, and then Auto-Fit the resultant columns.

Version and System Requirements


You must add references for the Microsoft.Office.Core to your solution from the .NET tab of the Visual Studio Add Reference dialog box, and the Microsoft Excel 12.0 Object Library (you can use 14.0 if you want, too, but nothing lower).

This code has been tested with Office 2007 and higher interop libraries.

Background


Sometimes, you will have an SSIS package or other process which might, say, extract records from a Database and put them into a Comma-Separated-Values (CSV) file.

CSV files are very useful in that they contain data in a compact, storage-effective format and can be imported into many a spreadsheet and database program, such as Excel.

Oftentimes, programmers find themselves with a client requirement to automate the process of sucking some CSV file into Excel.

Now For the Code


I wrote a method to import CSVs into Excel, coded as shown in Listing 1.

C#
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;

/// <summary>
/// Takes a CSV file and sucks it into the specified worksheet of this workbook at the specified range
/// </summary>
/// <param name="importFileName">Specifies the full path to the .CSV file to import</param>
/// <param name="destinationSheet">Excel.Worksheet object corresponding to the destination worksheet.</param>
/// <param name="destinationRange">Excel.Range object specifying the destination cell(s)</param>
/// <param name="columnDataTypes">Column data type specifier array. For the QueryTable.TextFileColumnDataTypes property.</param>
/// <param name="autoFitColumns">Specifies whether to do an AutoFit on all imported columns.</param>
public void ImportCSV(string importFileName, Excel.Worksheet destinationSheet,
    Excel.Range destinationRange, int[] columnDataTypes, bool autoFitColumns)
{
    destinationSheet.QueryTables.Add(
        "TEXT;" + Path.GetFullPath(importFileName),
    destinationRange, Type.Missing);
    destinationSheet.QueryTables[1].Name = Path.GetFileNameWithoutExtension(importFileName);
    destinationSheet.QueryTables[1].FieldNames = true;
    destinationSheet.QueryTables[1].RowNumbers = false;
    destinationSheet.QueryTables[1].FillAdjacentFormulas = false;
    destinationSheet.QueryTables[1].PreserveFormatting = true;
    destinationSheet.QueryTables[1].RefreshOnFileOpen = false;
    destinationSheet.QueryTables[1].RefreshStyle = XlCellInsertionMode.xlInsertDeleteCells;
    destinationSheet.QueryTables[1].SavePassword = false;
    destinationSheet.QueryTables[1].SaveData = true;
    destinationSheet.QueryTables[1].AdjustColumnWidth = true;
    destinationSheet.QueryTables[1].RefreshPeriod = 0;
    destinationSheet.QueryTables[1].TextFilePromptOnRefresh = false;
    destinationSheet.QueryTables[1].TextFilePlatform = 437;
    destinationSheet.QueryTables[1].TextFileStartRow = 1;
    destinationSheet.QueryTables[1].TextFileParseType = XlTextParsingType.xlDelimited;
    destinationSheet.QueryTables[1].TextFileTextQualifier = XlTextQualifier.xlTextQualifierDoubleQuote;
    destinationSheet.QueryTables[1].TextFileConsecutiveDelimiter = false;
    destinationSheet.QueryTables[1].TextFileTabDelimiter = false;
    destinationSheet.QueryTables[1].TextFileSemicolonDelimiter = false;
    destinationSheet.QueryTables[1].TextFileCommaDelimiter = true;
    destinationSheet.QueryTables[1].TextFileSpaceDelimiter = false;
    destinationSheet.QueryTables[1].TextFileColumnDataTypes = columnDataTypes;

    Logger.GetInstance().WriteLog("Importing data...");
    destinationSheet.QueryTables[1].Refresh(false);

    if (autoFitColumns==true)
        destinationSheet.QueryTables[1].Destination.EntireColumn.AutoFit();

    // cleanup
    this.ActiveSheet.QueryTables[1].Delete();
}


Listing 1. Inserting CSV data into Excel.

Usage Notes


Here's an example of how to call this method:

C#
myOwnWorkbookClass.ImportCSV(
     @"C:\MyStuff\MyFile.CSV",
     (Excel.Worksheet)(MyWorkbook.Worksheets[1]),
     (Excel.Range)(((Excel.Worksheet)MyWorkbook.Worksheets[1]).get_Range("$A$7")),
     new int[] { 2, 2, 2, 2, 2 }, true);


Listing 2. How to call the ImportCSV method.

Things to Keep in Mind


Arrays in Excel Are One-Based



Keep in mind that the MyWorkbook object is a Excel.Workbook object and we are accessing the first Excel.Worksheet in the MyWorkbook.Worksheets array. Make sure you remember that in Excel, arrays are one-based, not zero-based; i.e., array[1] is the first element of Excel arrays.

Casting


Casting is very important, since stuff comes out of Excel Interop arrays and properties as objects most of the time. So you have to be sure and cast your parameters correctly.

Specifying the Data Types for Your Input Columns


Notice that I input the parameter value new int[] { 2, 2, 2, 2, 2 } in the call to the ImportCSV method in Listing 2. This parameter expresses the data types you want to format the destination Excel columns as. These are the types found under the Format > Cells menu item.

How do we know which numbers to put? First of all, there must be the same number of values in this array as there are columns in your CSV file. So my CSV file here has 5 columns, hence the array has 5 values.

Secondly, the parameter fills in the TextFileColumnDataTypes property of the QueryTable object representing the destination of the import. The hyperlinked text refers to the MSDN Library reference. In the reference, it gives you Xl* enumeration constant values. The 2's in the value above just happpen to stand for the xlTextFormat enumeration value in Excel 2007. Use this property only when your query table is based on data from a text file (with the QueryType property set to xlTextImport). If you put more values in this parameter than there are columns in your text file, they will be ignored.



How do I know which numbers (1,2,3, etc.) correspond to xlGeneralFormat, xlTextFormat, etc.? I don't know for sure, but my suspicion is that, if you look at the table of choices in the web page linked above, and number the rows of the table from 1 to 10, the number corresponding to the row you want should be put into your int[] array.

Happy Importing!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
United States United States
Brian C. Hart, Ph.D., is a strategic engagement leader on a mission to leverage space technology to protect U.S. interests and assets against adversaries. Throughout Dr. Hart's career, he has enjoyed: Working closely with business executives to provide strategic direction and leadership, translating customer and competitive intelligence into compelling capture strategies and solutions, and mentoring teams to enhance individual and company capabilities while fostering an engaging and accountable environment, being involved in STEAM initiatives and education to develop greater awareness in the community, and serving the armed forces with the U.S. Navy and U.S. Army National Guard. He is excited to begin developing his career in Jacobs's Critical Mission Systems business unit, supporting NORAD and the U.S. Space Force.

Comments and Discussions

 
QuestionGreat article! How about character encoding? Pin
Scientific Mitch28-Nov-15 16:19
Scientific Mitch28-Nov-15 16:19 
GeneralVery useful Pin
Sivaji15653-Apr-14 0:45
Sivaji15653-Apr-14 0:45 
QuestionWhat if the csv contains German characters Pin
Nikhil Khurana20-Mar-14 17:33
Nikhil Khurana20-Mar-14 17:33 
GeneralExcellent Pin
anil Madan20-Dec-10 8:20
anil Madan20-Dec-10 8:20 
GeneralMy vote 5 for good work! Pin
Abdul Quader Mamun17-Dec-10 5:19
Abdul Quader Mamun17-Dec-10 5:19 
GeneralThanks for sharing. Pin
Slacker00717-Dec-10 0:27
professionalSlacker00717-Dec-10 0:27 
GeneralThanks for the tip. Pin
Dr.Walt Fair, PE16-Dec-10 13:15
professionalDr.Walt Fair, PE16-Dec-10 13:15 
GeneralGood tips Pin
Abdul Quader Mamun16-Dec-10 8:33
Abdul Quader Mamun16-Dec-10 8:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.