开发者

Cut and paste entire Excel column

I'm looking for s开发者_StackOverflowome 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):

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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜