Home » excel » c# – Cut and paste entire Excel column

c# – Cut and paste entire Excel column

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m looking for some sample code on how to cut and paste an entire column in Excel.

How to&Answers:

Assuming you know how to cut and paste a range, then just specify the range using the column letter. eg. Range("A:A") specifies the whole of column A.

Answer:

Here’s a sample the cuts and pastes a row. Converting it to a column should be trivial

Answer:

My first question is – do you have to read from an Excel file? Is it possible, export to a CSV or something else. This may be easier.

Otherwise, you can do something like this (assuming you already have the reference to the Excel object):

xlobj.workbook("workbook1.xls").sheets("Sheet1").Columns("C:C").Cut
xlobj.workbook("workbook1.xls").sheets("Sheet1").Columns("A:A").Paste

Answer:

Using Microsoft Excel 12.0 Object Library (Microsoft.Office.Interop.Excel)

Application app = new Application();
Workbook wb = app.Workbooks.Open("test.xlsx");
Worksheet ws = wb.Sheets["MyTestSheet"];
Range rngSource = ws.UsedRange.Columns["A"];
Range rngTarget = ws.UsedRange.Columns["D"];
rngTarget.Value = rngSource.Value;
rngSource.Value = null;
wb.Save();
app.Application.Quit();

You can do the same with fewer lines of code, but for demonstration purposes I’ve written it that way. Bear in mind that the above code violates the “Never use 2 dots when referring to COM objects”, which might cause trouble disposing the COM objects and leave zombie Excel processes.

Answer:

Use the ‘EntireColumn’ property, that’s what it is there for:

string rangeQuery = "A1:A1";

Range range = workSheet.get_Range(rangeQuery, Type.Missing);

range = range.EntireColumn;