简体   繁体   English

如何以编程方式删除列?

[英]How to Delete a Column Programmatically?

How does one delete a column (or multiple columns) in Excel?如何在 Excel 中删除一列(或多列)?

eg.例如。 How to delete column C and shift the rest left?如何删除C列并将其余的左移?

Here is the solution to make it clearer (thanks to Leniel for the link)这是使其更清晰的解决方案(感谢Leniel提供链接)

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

This was the first result I hit and deleting a column in Excel doesn't need as much code as the current answers suggest.这是我命中的第一个结果,删除 Excel 中的列不需要像当前答案所建议的那么多代码。 In fact (assuming you have a Worksheet object already, listed below as mySheet ) all that is needed for the original question is:事实上(假设您已经有一个Worksheet对象,在下面列为mySheet )原始问题所需的一切是:

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 ) ie 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.您可以在Delete方法中指定一个变量(请参阅https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.xldeleteshiftdirection?view=excel-pia )即mySheet.Columns["C"].Delete(xlShiftToLeft)但没有必要,因为Delete方法足够智能,可以意识到您选择的Range是单列,因此会自动执行此操作。

You can also uses a numeric value to designate the column ie mySheet.Columns[2].Delete()您还可以使用数值来指定列,即mySheet.Columns[2].Delete()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM