Excel插入行(不是添加)

use*_*207 4 .net c# excel c#-4.0

我有一个Excel '07模板文件用于采购订单.在模板上,只有3行项目的空间,然后模板显示总计.

所以,基本上,在模板中它有:第19行 - 第20行 - 项目第21行 - 第22行 - 项目总数

显然,大多数购买将有超过3项.那么在打印出3个项目后,如何在21到22之间插入一行?

编辑; 所以这就是我所拥有的:

            xlApp.Workbooks.Open(template, misValue, misValue, misValue, 
                misValue, misValue, misValue, misValue, misValue, misValue, 
                misValue, misValue, misValue, misValue, misValue); 

int row = 19;
if (poDetailBO1.MoveFirst())
            {
                do
                {
                    itemsBO3.FillByPK(poDetailBO1.Style);
                    if (row < 22)
                    {


                        xlApp.Cells[row, 1] = poDetailBO1.LineNo;
                        xlApp.Cells[row, 2] = itemsBO3.Factory;
                        xlApp.Cells[row, 3] = poDetailBO1.Style;
                        xlApp.Cells[row, 4] = itemsBO3.UPC_Code;
                        xlApp.Cells[row, 5] = itemsBO3.Item_Description;
                        xlApp.Cells[row, 6] = "TARRIFF"; //To be replaced later
                        xlApp.Cells[row, 7] = itemsBO3.Plate_Color;
                        xlApp.Cells[row, 8] = itemsBO3.Color;
                        xlApp.Cells[row, 9] = poDetailBO1.PrePack;
                        xlApp.Cells[row, 10] = itemsBO3.Cost;
                        xlApp.Cells[row, 11] = poDetailBO1.Qty;
                        xlApp.Cells[row, 12] = poDetailBO1.Qty * itemsBO3.Cost;

                        row++;
                    }
                    else if (row >= 22)
                    {
                        Excel.Range r = xlWorkSheet.Range[xlWorkSheet.Cells[row, misValue], xlWorkSheet.Cells[row, misValue]];
                        r.Insert(Excel.XlInsertShiftDirection.xlShiftDown, misValue);
                        r.Value2 = "GOBBLYDEEGOOK";

                        row++;
                    }
                } while (poDetailBO1.MoveNext());
Run Code Online (Sandbox Code Playgroud)

但是,我的Insert插入到错误的工作表中,哈.而不是我想象它插入的地方 - 第2行,第19栏.

Sid*_*and 9

首先,我没有看到你在哪里设置你的,xlWorksheet但这将是我检查的第一个地方,看看为什么你的单元格被插入错误的工作表.

其次,我认为您的Excel.Range对象设置不正确.您可能遇到麻烦,因为您只是在WorkSheet.Cells属性中指定行号而不是列名.当我尝试使用时,我会在使用的细胞范围之后插入细胞,而不是我想要的位置.我倾向于使用对象的get_Range()方法,Worksheet因为它通常以更可预测的方式工作.

鉴于所有这些,根据您是希望特定单元格向下移动还是整行,您可以使用以下之一:

// To shift down a set of cells from columns A to F

Excel.Range r = xlWorkSheet.get_Range("A" + row.ToString(), "F" + row.ToString());
r.Insert(Excel.XlInsertShiftDirection.xlShiftDown);

// To shift down all of a row

Excel.Range r = xlWorkSheet.get_Range("A" + row.ToString(), "A" + row.ToString()).EntireRow;
r.Insert(Excel.XlInsertShiftDirection.xlShiftDown);
Run Code Online (Sandbox Code Playgroud)