• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

C# Importing Excel

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

RedDragonXXX

Senior RAM Pornographer
Joined
Mar 3, 2005
Location
Jacksonville, FL
I'm writing a program that will essentially import new set of data into previously created excel sheet (deleting everything else) using C# / Visual Studio 2010 and I wanted to know if such thing is possible?

I know how to do it with text files, but I have never done it with .xls files. If anyone has any links or suggestions please let me know. I'm new to C# but I get most of the stuff since the syntax is similar to Java and VB.
 
Hey RedDragon,

You are trying to import data into an excel spreadsheet? What kind of data?

http://social.msdn.microsoft.com/Fo...l/thread/ef11a193-54f3-407b-9374-9f5770fd9fd7

Thats the first thing that comes to mind for me..


further down the in the comments:

Excel.Application excelApp = new Excel.Application();
string myPath = @"C:\Excel.xls";
excelApp.Workbooks.Open(myPath);
int rowIndex = 1; int colIndex = 1;

excelApp.Cells[rowIndex, colIndex] = "First";
excelApp.Visible = true;


That will open the workbook named Excel.xls located in your C:\ directory. rowIndex controls which row you're in and assumingly so, colIndex controls the column you are in. The code will place the word "First" into the workbook in cell "A1". The visible method tells your program to make "excelApp" visible. You can of course save/close the workbook without displaying it first.
 
Last edited:
Data that I'm importing is another .xls file that has same format. Basically we have one huge database in .xls format and instead of appending data to it which will make it even bigger, I just want to overwrite that existing data with the new data set (from .xls file) that I will be importing.
 
If its going to delete the data in the existing workbook entirely, I would just delete the workbook, create a new one, and rename it to match the old deleted one. Then just populate it with the data..

Going 1 step further, if the formatting and data etc are exactly what you want in the destination workbook, I would just delete the workbook, copy the source workbook into the destination workbook all at once, instead iterating through the rows and columns..
 
I don't want to delete the workbook since I will be constantly updating data to it. It only contains one worksheet with bunch of data in it.

I just need to import new data to that worksheet (.xls format) and each time I import the old data will be replaced with new data that I import from a different .xls worksheet.

Working with Java I know that this can easily be done with text files, I just want to see if there is a way to do it in C# using .xls files.
 
I don't want to delete the workbook since I will be constantly updating data to it. It only contains one worksheet with bunch of data in it.

I just need to import new data to that worksheet (.xls format) and each time I import the old data will be replaced with new data that I import from a different .xls worksheet.

Working with Java I know that this can easily be done with text files, I just want to see if there is a way to do it in C# using .xls files.

So you want to delete old data and replace it, but not necessarily delete ALL the data?

Short answer is yes you can do it in C# with excel files. The .net library allows the developer to do this quite easily.. If you see the example I listed, the code shows how to do it..
 
So you want to delete old data and replace it, but not necessarily delete ALL the data?

Short answer is yes you can do it in C# with excel files. The .net library allows the developer to do this quite easily.. If you see the example I listed, the code shows how to do it..

Yep, when I import new .xls file it should delete all of the old data. Normally I would keep the header, but the .xls file that is being imported contains the same header in all of the files.

Does the code that you listed do this or something different? I looked over it and can't really tell as C# syntax is new to me.
 
Yep, when I import new .xls file it should delete all of the old data. Normally I would keep the header, but the .xls file that is being imported contains the same header in all of the files.

Does the code that you listed do this or something different? I looked over it and can't really tell as C# syntax is new to me.

Check out this sample code:

http://www.eventhorizontech.net/mystuff/ExcelTest.zip

put the Excel.xls file in your C: root..

fire up the solution.. you can then hit Import! and it will open the Excel.xls file, write the data supplied in the text box and then show the spreadsheet for you to view..

Alternatively, if you are uncomfortable downloading any of the files.. here is the code I used for this:

http://pastebin.com/20kAzUPd

You dont have to use the Excel.xls I supplied.. Just create a new file in your C: called 'Excel.xls' and save it blank.
 
Last edited:
I gave it a test and it seems to do what I'm looking for except that it imports text from the text box and I'm looking to import other .xls files. Couple of questions;

1. Is it possible to provide path where the text will be imported or does it look for Excel.xls by default? For example could I specify that it imports data into different location/file like test.xls located in C:\Users\Test\Downloads\test.xls.

2. Is this set up to only import one line? Looking at the code doesn't seem to iterate the row and column.
 
I gave it a test and it seems to do what I'm looking for except that it imports text from the text box and I'm looking to import other .xls files. Couple of questions;

1. Is it possible to provide path where the text will be imported or does it look for Excel.xls by default? For example could I specify that it imports data into different location/file like test.xls located in C:\Users\Test\Downloads\test.xls.

2. Is this set up to only import one line? Looking at the code doesn't seem to iterate the row and column.

Heh, I was just trying to provide a little example code to show you how to reference the MS office / Excel libraries and the underlying C# a bit!

If you know java, you should be able to easily write looping code (if its needed) to import the data..

What I was getting at earlier is that unless you need to keep something in it, if the entire workbook's (not the whole excel file, just the particular workbook that is) is being updated, why not just delete the particular workbook, and then add a new one in that has the new data?

I can help you further along if you need it, but right now I have to get some stuff done here at work :(
 
I've been playing around with this code and wrote some stuff that will read a text file and import it to Excel, but then I noticed that it won't compile because of this error:

SUlzw.png

Any idea why its showing this? Is there something else I have to import?
 
Quick follow up. Program is progressing nicely and so far works as I wanted it to. Way I have it working is, I have it set up so the user can choose source and destination file. Source file will be text file that will be imported to .xls file and destination file is the file where the .txt data is going.

Want I wanted to know since the destination file will always be the same but may be stored in different locations on users machines (why I gave them option to choose the destination file instead of setting it to static location) is there a way I can tell it that every time it opens up that it empties out all the data?

Here is the code:

Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using Excel = Microsoft.Office.Interop.Excel;

namespace LibAnswersImport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        OpenFileDialog ofd = new OpenFileDialog();

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtFileName.Text = ofd.SafeFileName;
                txtFilePath.Text = ofd.FileName;
            }

        }

        private void btnDestination_Click(object sender, EventArgs e)
        {
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtDestination.Text = ofd.FileName;
                
            }

        }
                
        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            int counter = 0;
            int rowIndex = 0;
            int colIndex = 0;
            string line;
            string data = txtDestination.Text;
                        
            Excel.Application excelApp = new Excel.Application();

            excelApp.Workbooks.Open(data);
            
            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(txtFilePath.Text);
            
            while ((line = file.ReadLine()) != null)
            {
                Console.WriteLine(line);

                //Does the incrementing
                counter++;
                rowIndex++;
                colIndex++;

                //Makes sure data stays in one column
                if (colIndex > 1)
                    colIndex--;

                //Writes data to the cell
                excelApp.Cells[rowIndex, colIndex] = line;
                
            }

            file.Close();

            excelApp.Visible = true;

            rtbOutput.AppendText("File Import Successfull!\n\n" + 
                "File contained " + counter + " lines of text");
                        
            // Suspend the screen.
            Console.ReadLine();
        }
               
                
    }
}
 
Yep, but now they want me to delimit the data into separate cells in excel which is giving me a headache.

Problem is data is tab delimited and there are bunch of null entries. Oh and each data item is surrounded in double quotation marks like so.

"test" "test" "test" empty "test" ...
 
Ack. Sounds like a bit of work :( AH the joys of programming. It is kicking me in the butt here as well.
 
Back