4

I want to write a program that saves the text in textbox to an Excel file using a loop because I want to insert multiple text into Excel. I found codes but it only overwrites data in cells. I want the program to find the last row and insert new data into the next row. I'm stuck here, please someone help me how to do that in c#.

object misValue = System.Reflection.Missing.Value;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

xlWorkSheet.Cells[1, 1] = "FirstName";
xlWorkSheet.Cells[1, 2] = "LastName";
xlWorkSheet.Cells[1, 3] = "JobTitle";
xlWorkSheet.Cells[1, 4] = "Address";

for (int i=2; i<=6; i++)
{
    xlWorkSheet.Cells[i, 1] = textBox1.Text;
    xlWorkSheet.Cells[i, 2] = textBox2.Text;
    xlWorkSheet.Cells[i, 3] = textBox3.Text;
    xlWorkSheet.Cells[i, 4] = textBox4.Text;
}
Rohit
  • 10,056
  • 7
  • 50
  • 82
akk
  • 45
  • 1
  • 1
  • 6
  • Why are you using a loop? The above code will write to cells in a loop. Shouldn't you be putting the above code in say a button click and then simply write to the last row? – Siddharth Rout Oct 14 '13 at 07:37

2 Answers2

4

Like I mentioned that you don't need to use a loop. See this example

Let's say your form looks like this.

enter image description here

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 Excel = Microsoft.Office.Interop.Excel;

Namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        Public Form1()
        {
            InitializeComponent();
        }

        //~~> Open File
        private void button1_Click(object sender, EventArgs e)
        {
            xlexcel = new Excel.Application();

            xlexcel.Visible = true;

            // Open a File
            xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 0, true, 5, "", "", true,
            Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

            xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

            xlWorkSheet.Cells[1, 1] = "FirstName";
            xlWorkSheet.Cells[1, 2] = "LastName";
            xlWorkSheet.Cells[1, 3] = "JobTitle";
            xlWorkSheet.Cells[1, 4] = "Address";
        }

        //~~> Add Data
        private void button2_Click(object sender, EventArgs e)
        {
            int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1 ;

            xlWorkSheet.Cells[_lastRow, 1] = textBox1.Text;
            xlWorkSheet.Cells[_lastRow, 2] = textBox2.Text;
            xlWorkSheet.Cells[_lastRow, 3] = textBox3.Text;
            xlWorkSheet.Cells[_lastRow, 4] = textBox4.Text;
        }

        //~~> Once done close and quit Excel
        private void button3_Click(object sender, EventArgs e)
        {
            xlWorkBook.Close(true, misValue, misValue);
            xlexcel.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlexcel);
        }

        private void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch (Exception ex)
            {
                obj = null;
                MessageBox.Show("Unable to release the Object " + ex.ToString());
            }
            finally
            {
                GC.Collect();
            }
        }
    }
}

FOLLOWUP FROM COMMENTS

Range object is a part of worksheet object. So you shouldn't be getting any errors there. And Like I mentioned above, the code is tried and tested.

enter image description here

MORE FOLLOWUP (From Comments)

The above code was tested on VS 2010 Ultimate. If you have VS 2008 then replace the line

int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count,
               1].End[Excel.XlDirection.xlUp].Row + 1;

with

int _lastRow = xlWorkSheet.Cells.Find(
                                      "*",
                                      xlWorkSheet.Cells[1,1],
                                      Excel.XlFindLookIn.xlFormulas,
                                      Excel.XlLookAt.xlPart,
                                      Excel.XlSearchOrder.xlByRows,
                                      Excel.XlSearchDirection.xlPrevious,
                                      misValue,
                                      misValue,
                                      misValue
                                      ).Row + 1 ;
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • `xactly i wntd same thng...thnx bro.... – user2877742 23 secs ago` I thought so :) – Siddharth Rout Oct 14 '13 at 08:23
  • getting a problem in the above code regarding :- Property, indexer, or event 'Range' is not supported by the language; try directly calling accessor method 'Microsoft.Office.Interop.Excel._Worksheet.get_Range(object, object)' wt shld b needed to do...?? – akk Oct 14 '13 at 11:49
  • in this line:- int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1 ; – akk Oct 14 '13 at 11:51
  • @SiddharthRout: How do you get xlWorkSheet.Range for exel worksheet object? I don't see Range option for Excel worksheet (interop). – Sangram Nandkhile Oct 15 '13 at 09:24
  • @Sangram: Because I know `Range` is a part of `xlWorkSheet` like I know `xlWorkSheet` is a part of `xlexcel` Please note that the above code is tired and tested. I am surprised that you are not getting that in intellisense. Updating my above post with a screenshot – Siddharth Rout Oct 15 '13 at 10:10
  • @SiddharthRout :This is what i see http://i.imm.io/1is2y.png Just figured out the reason. You are probably using .net framework 4. .net 3.5 doesn't have such option. – Sangram Nandkhile Oct 15 '13 at 10:22
  • @Sangram: which VS version are you using? – Siddharth Rout Oct 15 '13 at 10:23
  • int _lastRow = xlWorkSheet.Range["A" + xlWorkSheet.Rows.Count].End[Excel.XlDirection.xlUp].Row + 1 ; Property, indexer, or event 'Range' is not supported by the language; try directly calling accessor method 'Microsoft.Office.Interop.Excel._Worksheet.get_Range(object, object)' – akk Oct 15 '13 at 10:25
  • @Akk: Which VS version are you using as well? – Siddharth Rout Oct 15 '13 at 10:25
  • Ah! I have not worked with 2008 for a very long time now. I have VS 2010 ultimate. – Siddharth Rout Oct 15 '13 at 10:32
  • Let me remote into a pc of a friend who has 2008. will post back shortly – Siddharth Rout Oct 15 '13 at 10:36
  • @akk: Do you have teamviewer? – Siddharth Rout Oct 15 '13 at 10:39
  • @Akk: Also test this for me.. What do you get? `int _lastRow = xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1].End[Excel.XlDirection.xlUp].Row + 1 ;` Replace this line with the other line – Siddharth Rout Oct 15 '13 at 10:44
  • error:- 'object' does not contain a definition for 'End' and no extension method 'End' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) – akk Oct 15 '13 at 10:50
  • Damn VS 2008! LOL. At lease the Range object problem is now solved... let me do few more tests. – Siddharth Rout Oct 15 '13 at 10:52
  • @akk: Check the updated post. See `MORE FOLLOWUP (From Comments)` in the above post. – Siddharth Rout Oct 15 '13 at 11:15
  • @siddhrth....d prblm is solved bro....jst 1 thng wen i open the xcelfile and write the textbox values ......it ss\uccsflly appnds inside the xcel file bt aftr dat the zcel file demands a differnt name to b saved wd.....for eg;- i hd excel.xls file bt aftr appending txtbx values inside excel.xls file.....a window opens and demands 2 b svd wd a diffrnt name other than excel.xls file... – akk Oct 15 '13 at 11:37
  • i jst wnt d same file to b rewritten wd values evrytime i insert...@siddhrth – akk Oct 15 '13 at 11:38
  • @akk: Yes that is because I was opening the file in readonly mode for testing. See the line `xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);` Change the paramenter for readonly. – Siddharth Rout Oct 15 '13 at 11:38
  • Glad to be of help :) – Siddharth Rout Oct 15 '13 at 11:43
  • @Sangram: Hope it is sorted for you as well? – Siddharth Rout Oct 15 '13 at 11:54
  • @SiddharthRout: Yes definitely. I was really lost when i realized i didn't have Worksheet.Range property :D – Sangram Nandkhile Oct 15 '13 at 12:06
0

Your main concern is to find the last used row in your excel.

For that you can use

 Excel.Range usedRange = xlWorkSheet .UsedRange;
 Excel.Range _lastCell= usedRange.SpecialCells(Excel.XlCellType.xlCellTypeLastCell,  
 Type.Missing);

  int _lastRow= lastCell.Row; // Gives you the last used row in your Excel sheet
  int _lastCol = lastCell.Column; // Give you the last used column



 _lastRow++; // To get the next row 

    for (int i=_lastRow; i<=_lastrow+6; i++) // Set your i value to _lastRow
    {
        xlWorkSheet.Cells[i, 1] = textBox1.Text;
        xlWorkSheet.Cells[i, 2] = textBox2.Text;
        xlWorkSheet.Cells[i, 3] = textBox3.Text;
        xlWorkSheet.Cells[i, 4] = textBox4.Text;
    }
Rohit
  • 10,056
  • 7
  • 50
  • 82
  • bro dis is nt solving my prblm.......i want to insert different data each time i insert a diffeerent value in textbox........bt it shows the same value six times in a row(i<=6) and repeating the previou one.... – akk Oct 14 '13 at 05:54
  • I have made slight changes in code Lets say the last used row in excel sheet is 10 then according to the code your values are written at [11,1][11,2].....[12,1][12,2]...[13,1],[13,2]...[16,1][16,2][16,3][16,4] Now when you run this whole code again next time the last row value you get is 16 and then the loop values are written at [17,1][17,2]... so where are the values overwritten ???? – Rohit Oct 14 '13 at 06:00
  • bt hw cn i insert a new value to the last row without replacing the previous one.......my main concern is dat,,.....??bcoz i m runiing the code it says replace the pprevious file.....i dnt wnt 2 replace the previous file – akk Oct 14 '13 at 06:05
  • I guess it is asking to replace the excel file ...for that you have to save the excel file and then open it again in next time – Rohit Oct 14 '13 at 06:09
  • yes it is aassking to replace the existing file.....nd wen i replce it ....it shows new data.....nd i dnt replace it....den error occurs... – akk Oct 14 '13 at 06:14
  • @Kyle: You should never use `UsedRange` to find the last row. It's highly unreliable. You might want to see [THIS](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba) – Siddharth Rout Oct 14 '13 at 08:27