S Andrew S Andrew - 1 year ago 65
C# Question

Adding extra data to an already created Excel sheet in C#

I am creating a simple application in C# where I am saving the data in an already created Excel sheet. To do this, first I am reading the data from the rows and if that row is empty that means I have to save my new data in it. I have an excel sheet with following details:

S.No | Name | Email ID | Phone Number

So I first check which is the last
. Let's say if it is 4, this means I have to enter data in 6th row with
S.No = 5
because one row is taken by the header.

To do this I am first opening the excel file and then scanning the rows. I am able to scan it but when I try to save it, it replace the current file with new one and old data is lost. Here is what I am doing:

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("<filepath>", 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;

for(parse = 2; parse <= 100; parse++)
if (xlRange.Cells[parse, 1].Value2 != null)

//Sno contains the recent serial number

After this I am just filling the data and saving the file:

xlWorksheet.Cells[Sno + 2, 1] = Sno + 1;
xlWorksheet.Cells[Sno + 2, 2] = NameTextBox.Text;
xlWorksheet.Cells[Sno + 2, 3] = EmailIdTextBox.Text;
xlWorksheet.Cells[Sno + 2, 4] = PhoneNumberTextBox.Text;

But at the time of saving it says file already exit because I am doing
. Is there any way to just save the file or any other alternative.

Please help.

Answer Source

For saving see this

Also consider the workaruond I said in comment.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download