Link to home
Start Free TrialLog in
Avatar of pavelmed
pavelmed

asked on

How to delete rows from Excel file by C# code?

I need to delete rows from an existing excel file.
I can open the file and read and write, but I also need  to delete rows from it.
I saw fome VB.NET examples but could not modify them to C#.

I use this code to open a file and a worksheet:

oXLMisc = new Excel.Application();
oWBMisc = oXLMisc.Workbooks.Open(miscFileName, 0, false, 5, "", "", true,
                    Excel.XlPlatform.xlWindows, "\t", false, false, 0, 0, 0, 0);
sheetsMisc = oWBMisc.Worksheets;
oSheetMisc = (Excel.Worksheet)sheetsMisc.get_Item(1);

But a statement like one if the two below fails.
oSheetMisc.get_Range("B1", "B300").Delete("Left");
OR
oSheetMisc.Rows.get_Range("B1", "B300").Delete("Left");

I'll appreciate your help.
Avatar of MuhammadAdil
MuhammadAdil
Flag of Pakistan image

ASKER CERTIFIED SOLUTION
Avatar of HeidarV
HeidarV

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pavelmed
pavelmed

ASKER

I could not use the info from Muhammad's suggestions, but Heidar's code worked well:
oSheetMisc.get_Range("A3", "A4").Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftToLeft);

It is just needed to repeat this as many times as there are cells in a row.

Thank you!