Import text file into excel using C#

coder_t2

Member
Nov 6, 2009
92
0
0
Hey guys, I am trying to import a text file into excel using C#. I do a lot of coding already for Excel using Visual Studio, but I am having trouble figuring how to access the import external data tool in Visual Studio. I am trying to avoid reading in the file line by line and importing myself since I am sure this built in tool is a lot more efficient and quicker. Any ideas? Is this even possible? Thank ahead of time.
 

vinylswing

Member
Apr 30, 2007
49
0
66
There is the From Text functionality under the Data tab in Excel 2007 that you could use to import the contents of text file.
 

PhatoseAlpha

Platinum Member
Apr 10, 2005
2,131
21
81
From http://support.microsoft.com/kb/306023 How to transfer data to an Excel workbook by using Visual C# 2005 or Visual C# .NET

Code:
// Open the text file in Excel.
m_objExcel = new Excel.Application();
m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks;
m_objBooks.OpenText(m_strSampleFolder + "Book6.txt", Excel.XlPlatform.xlWindows, 1, 
	Excel.XlTextParsingType.xlDelimited, Excel.XlTextQualifier.xlTextQualifierDoubleQuote,
	false, true, false, false, false, false, m_objOpt, m_objOpt, 
	m_objOpt, m_objOpt, m_objOpt);

m_objBook = m_objExcel.ActiveWorkbook;

// Save the text file in the typical workbook format and quit Excel.
m_objBook.SaveAs(m_strSampleFolder + "Book6.xls", Excel.XlFileFormat.xlWorkbookNormal, 
	m_objOpt, m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange, m_objOpt, m_objOpt,
	m_objOpt, m_objOpt);
m_objBook.Close(false, m_objOpt, m_objOpt);
m_objExcel.Quit();