Excel automation C#: How to delete a column?

2020-03-01 15:42发布

问题:

I am reading this (Excel Tasks) to automate some Excel operations in VS2008 C#
http://msdn.microsoft.com/en-us/library/syyd7czh%28v=VS.80%29.aspx

But I couldn't find how to delete a column (or multiple columns).

eg. How to delete column C and shift the rest left?

Thanks in advance.

回答1:

Here you find how to do it:

http://bytes.com/topic/c-sharp/answers/258110-how-do-you-delete-excel-column

http://quicktestprofessional.wordpress.com/2008/02/14/delete-columns-from-xl-sheet/



回答2:

Here is the solution to make it clearer (thanks to Leniel for the link)

Excel.Range range = (Excel.Range)sheet.get_Range("C1", Missing.Value);
range.EntireColumn.Delete(Missing.Value);
System.Runtime.InteropServices.Marshal.ReleaseComObject(range);


回答3:

This was the first result I hit and deleting a column in Excel doesn't need as much code as the current answers suggest. In fact (assuming you have a Worksheet object already, listed below as mySheet) all that is needed for the original question is:

mySheet.Columns["C"].Delete();

If you want to delete multiple columns then:

mySheet.Columns["C:D"].Delete();

You can specify a variable in the Delete method (see https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.xldeleteshiftdirection?view=excel-pia) i.e. mySheet.Columns["C"].Delete(xlShiftToLeft)but there's no need as the Delete method is smart enough to realise that the Range you are selecting is a single column, so will do this automatically.

You can also uses a numeric value to designate the column i.e. mySheet.Columns[2].Delete()