I am writing contents to an excel file through c#. I am having 4 columns and many rows in excel. When the application runs, I need to check if whether data is present in sheet1, then it should be moved to sheet2. If sheet2 also contains data, then it should be appended with sheet2 data. I am using interop dll for accessing excel. I have done with writing contents, but how I can move it programmatically? This is what I tried.
Excel.Workbook xlwb;
Excel.Application excelApp = new Excel.Application();
Excel.Worksheet xlssheet1;
Excel.Worksheet xlssheet2;
xlwb = excelApp.Workbooks.Open(myPath, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing,
objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
int rowIndex = 2; int colIndex = 1;
if (excelApp.Cells[rowIndex, colIndex] != null)
{
xlssheet1 = (Worksheet)xlwb.Worksheets[1];
xlssheet2 = (Worksheet)xlwb.Worksheets[2];
xlwb.Sheets.Move(System.Reflection.Missing.Value, xlssheet2);
xlwb.Save();
}
First of all I’d define a function to find out the last used row of a worksheet:
Then your code can iteratively copy the cells from one worksheet to the other in this way: