Saturday, February 7, 2009

Copy/Insert row from one sheet to another sheet in Excel using Interop.Excel in .NET

I was just trying to copy row in one excel file to another excel using Interop.Excel from .NET. I tried a lot but couldn't make it. It looks very simple at first view but normal Rows.Insert doesn't work in all cases. I googled a lot and then after a long time I found one solution to achieve this.

Have a look at following code to achieve this(if you're using interop.excel).

Dim xlApplication As New Excel.Application
xlApplication.Visible = False
Dim xlBook As Workbook
Dim xlBook_New As Workbook
Try
xlBook = xlApplication.Workbooks.Open("C:\Source.xls")
xlBook_New = xlApplication.Workbooks.Open("C:\Destination.xls")

xlBook.Worksheets("" & "Sheet1" & "").activate()
Dim xlSheet1 As Worksheet = xlBook.ActiveSheet
xlSheet1.Range("A1", "CP5").Select()
xlSheet1.Range("A1", "CP5").Copy()
xlApplication.Selection.copy()
xlBook_New.Worksheets("Sheet1").activate()
Dim xlSheet1_new As Worksheet = xlBook_New.ActiveSheet
xlSheet1_new.Activate()
Dim rng As Excel.Range = xlSheet1_new.Range("A2")
rng.EntireRow.Insert(XlInsertShiftDirection.xlShiftDown, XlInsertFormatOrigin.xlFormatFromRightOrBelow)

'Remove 3rd row
Dim rng1 As Excel.Range = xlSheet1_new.Range("A1").Offset(3, 0)
rng1.EntireRow.Delete(XlDeleteShiftDirection.xlShiftUp)

xlSheet1_new.Name = "Sheet1"
xlSheet1_new.Columns.AutoFit()

Catch ex As Exception
MsgBox(ex.Message)
Finally
Dim o As New Object
Clipboard.SetDataObject(0)
xlBook.Save()
xlBook.Close(False, Nothing, False)
xlBook = Nothing
xlBook_New.Save()
' Need all following code to clean up and remove all references!!!
xlBook_New.Close(Nothing, Nothing, Nothing)
xlBook_New = Nothing
xlApplication.Workbooks.Close()
xlApplication.Quit()
xlApplication = Nothing
End Try

Happy Programming!!!

No comments: