I’m looking for some sample code on how to cut and paste an entire column in Excel.
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.
Here’s a sample the cuts and pastes a row. Converting it to a column should be trivial
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):
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.
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;