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;
}
Like I mentioned that you don't need to use a loop. See this example
Let's say your form looks like this.
Code: (TRIED AND TESTED)
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.
MORE FOLLOWUP (From Comments)
The above code was tested on VS 2010 Ultimate. If you have VS 2008 then replace the line
with
Your main concern is to find the
last used row
in your excel.For that you can use