Click here to Skip to main content
15,881,027 members
Articles / Programming Languages / C#
Tip/Trick

Reading Text or CSV File and Saving It as Excel File (.xls or xlsx) using Microsoft Excel

Rate me:
Please Sign up or sign in to vote.
4.33/5 (3 votes)
21 Nov 2012CPOL 65.7K   9   12
Reading text or CSV file and saving it as an Excel file

Introduction

Sometimes, we need to read huge amounts of data from text or CSV files and convert or put the data into Excel. To do that, we need to create an Excel file first. We create the xlexcel application for opening Excel. And then, we create xlWorkbook and xlWorksheet. When we open a particular Excel workbook and worksheet, we need to set the range of where exactly the data needs to be posted and in which sheet the data needs to be presented, like sheet1 or sheet2 or so on.

After pasting the data, we would save the file with the required extension. We then close the particular file. If you want to watch the file, then we have to comment xlexcel.Quit() and uncomment xlexcel.Visible = true.

Then we can see the Excel file too.

Creating the Form

Creating xlsConvert

C#
private void btnXlsConvert_Click(object sender, EventArgs e)
{
    // Reading the text file - StreamReader include System.IO namespace
    StreamReader objReader = new StreamReader(@"received.txt");// Please give the file path
    string sLine = "";
    ArrayList arrText = new ArrayList();// Include System.Collections.Generic namespace
    while (sLine != null)
    {
        sLine = objReader.ReadLine();
        if (sLine != null)
            arrText.Add(sLine);
    }
    callExcel(arrText, true);
}

Creating xlsxConvert

C#
private void btnXlsxConvert_Click(object sender, EventArgs e)
{
    try
    {
        StreamReader objReader = new StreamReader(@"received.txt");// Please give the file path
        string sLine = "";
        ArrayList arrText = new ArrayList();
        while (sLine != null)
        {
            sLine = objReader.ReadLine();
            if (sLine != null)
                arrText.Add(sLine);
        }
        callExcel(arrText, false);
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
     }
}
private void callExcel(ArrayList arrText, bool value)
{
    try
    {
        // Change Your String here
        String textString = null;
        foreach (var item in arrText)
        {
            textString = textString + item + Environment.NewLine;
        }
        Clipboard.SetText(textString);
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        // for excel visibility
        //xlexcel.Visible = true;
        // Creating a new workbook
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        // Putting Sheet 1 as the sheet you want to put the data within
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        // creating the range
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.Paste(CR, false);
        if (value == true)
        {
            try
            {
                // saving the file as .xls
                xlWorkSheet.SaveAs(@"C:\Users\U0153056\Desktop\receivedNew.xls");
            }
            catch (Exception)
            {
                MessageBox.Show("File already exist");
            }
        }
        else
        {
            try
            {
                // saving the file as .xlsx
                xlWorkSheet.SaveAs(@"C:\Users\U0153056\Desktop\receivedNew.xlsx");
            }
            catch (Exception)
            {
                MessageBox.Show("File already exist");
            }
        }
        xlexcel.Quit();
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Before you execute this application, you are supposed to include using the Excel= Microsoft.Office.Interop.Excel namespace. For this, we need to add the namespace in the references (right click on References and click on Add Reference and then select Microsoft.Office.Interop.Excel).

License

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


Written By
Web Developer
India India
I am a 29 year old software Web Developer from Hyderabad, India. I have been working since approximately age 25. Where as in IT Development industry since 27. I am Microsoft Certified Technology Specialist.

I have taught myself in development, beginning with Microsoft's technologies ASP.NET, Approximately 3 years ago, I was given an opportunity to work as a freelance in the tech field. Now I am working as a web developer where my roles make me purely in web based technology solutions which manage and control access to applications and patient information stored in legacy systems, client-server applications.

I too had an opportunity to train some IT professionals with technical skills in development area. Which became my passion.

I have worked on various .NET framework versions(2.0 , 3.5, 4.0) and have been learning every new technology being introduced. Currently, I am looking forward to working in R & D in .Net to create distributed, reusable applications.

Comments and Discussions

 
AnswerMessage Closed Pin
24-Jul-13 22:14
henryshaw198324-Jul-13 22:14 
GeneralRe: Try this Cloud API Pin
Mannava Siva Aditya24-Jul-13 22:19
Mannava Siva Aditya24-Jul-13 22:19 
Generalxlexcel.Quit() is right Pin
shreyansh shah21-Nov-12 4:54
shreyansh shah21-Nov-12 4:54 
If you have not mentioned xlexcel.Quit() when we execute the application in the background the xls file would be opened as well as a temp file (which has name starting with ~$) would be created. Great post.
GeneralRe: xlexcel.Quit() is right Pin
Mannava Siva Aditya24-Jul-13 19:17
Mannava Siva Aditya24-Jul-13 19:17 
GeneralMy vote of 3 Pin
Lakshmi Ganesh20-Nov-12 22:26
Lakshmi Ganesh20-Nov-12 22:26 
GeneralNice Article Pin
Paritosh Soni20-Nov-12 20:28
Paritosh Soni20-Nov-12 20:28 
SuggestionCreating Excel file without interop Pin
Vijay Gehani20-Nov-12 20:25
Vijay Gehani20-Nov-12 20:25 
GeneralRe: Creating Excel file without interop Pin
Mannava Siva Aditya24-Jul-13 19:16
Mannava Siva Aditya24-Jul-13 19:16 
SuggestionA few words about COM interop... Pin
Steven M Hunt20-Nov-12 8:35
Steven M Hunt20-Nov-12 8:35 
GeneralRe: A few words about COM interop... Pin
Mannava Siva Aditya20-Nov-12 20:03
Mannava Siva Aditya20-Nov-12 20:03 
QuestionCrude Pin
gashach20-Nov-12 5:57
gashach20-Nov-12 5:57 
AnswerRe: Crude Pin
Mannava Siva Aditya20-Nov-12 19:58
Mannava Siva Aditya20-Nov-12 19:58 

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.