Click here to Skip to main content
Licence CPOL
First Posted 22 Sep 2006
Views 24,032
Bookmarked 14 times

How to programmatically open a text file in Excel using VSTO

By | 22 Sep 2006 | Article
We can easily start Excel and open a given workbook - however, it takes some trickery to open a text file without using the commandline.

How to open a txt/prn file programmatically in Excel

Given that Excel takes no arguments on the command-line, how do we programmatically open a file with other types than workbook? This took me some hours to figure out. Hope this solution helps someone else to avoid going down a long track of making macros and whatnot.

  1. Ensure the Office Interop DLLs are installed (PIAs).
  2. Code away.

Here is the complete code:

using System.Globalization;
using Excel = Microsoft.Office.Interop.Excel;

//wrap in some class ..

//ms-help://MS.VSCC.v80/MS.MSDN.vAug06.en/offioxl11ref/html/
//           M_Microsoft_Office_Interop_Excel_Workbooks_OpenText_3_1a91c0ff.htm
public static void OpenTxtInExcel(string name, string filename)
{
    Excel.Application application = new Excel.Application();
    object missing = System.Reflection.Missing.Value;
    System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
    application.Caption = name;
    application.Visible = true;
    application.Workbooks.OpenText
    (
        filename,
        missing,
        1,
        missing,
        Excel.XlTextQualifier.xlTextQualifierNone,
        missing,
        missing,
        missing,
        true, //COMMA
        missing,
        missing,
        missing,
        missing,
        missing,
        missing,
        missing,
        missing,
        missing
    );
}

License

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

About the Author

Casper Leon Nielsen

Architect
HelloGroup
Denmark Denmark

Member

Casper Leon Nielsen is a MCP/MCAD and is currently employed by HelloGroup a/s - a technical savy (yes that whats they are calling it these days) company.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 22 Sep 2006
Article Copyright 2006 by Casper Leon Nielsen
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid