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.
- Ensure the Office Interop DLLs are installed (PIAs).
- Code away.
Here is the complete code:
using System.Globalization;
using Excel = Microsoft.Office.Interop.Excel;
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,
missing,
missing,
missing,
missing,
missing,
missing,
missing,
missing,
missing
);
}