0

我正在通过 c# 将内容写入 excel 文件。我在 excel 中有 4 列和许多行。当应用程序运行时,我需要检查 sheet1 中是否存在数据,然后将其移动到 sheet2。如果 sheet2 还包含数据,则应附加 sheet2 数据。我正在使用互操作 dll 来访问 excel。我已经完成了内容的编写,但是如何以编程方式移动它?这是我尝试过的。

  Excel.Workbook xlwb;
  Excel.Application excelApp = new Excel.Application();
  Excel.Worksheet xlssheet1;
  Excel.Worksheet xlssheet2; 
 xlwb = excelApp.Workbooks.Open(myPath, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing,
                                    objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
            int rowIndex = 2; int colIndex = 1;
            if (excelApp.Cells[rowIndex, colIndex] != null)
            {
                xlssheet1 = (Worksheet)xlwb.Worksheets[1];
                xlssheet2 = (Worksheet)xlwb.Worksheets[2];

                xlwb.Sheets.Move(System.Reflection.Missing.Value, xlssheet2);
                xlwb.Save();                

            }
4

2 回答 2

2

首先,我会定义一个函数来找出工作表中最后使用的行:

private int LastUsedRow(Excel.Worksheet aSheet)
{
    object hmissing = System.Reflection.Missing.Value;
    string usedAddress = aSheet.UsedRange.get_Address(hmissing, hmissing, Excel.XlReferenceStyle.xlA1, hmissing, hmissing);
    return int.Parse(usedAddress.Substring(usedAddress.LastIndexOf('$') + 1));
}

然后您的代码可以通过这种方式将单元格从一个工作表迭代复制到另一个工作表:

Excel.Workbook xlwb;
Excel.Application excelApp = new Excel.Application();
Excel.Worksheet xlssheet1;
Excel.Worksheet xlssheet2; 
xlwb = excelApp.Workbooks.Open(myPath, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing, objMissing);
xlssheet1 = (Worksheet)xlwb.Worksheets[1];
xlssheet2 = (Worksheet)xlwb.Worksheets[2];
int lastRow1 = LastUsedRow(xlssheet1);
int lastRow2 = LastUsedRow(xlssheet2);
int curRow = lastRow2 + 1;
for (int i = 1; i <= lastRow1; i++)
{
    object toCopy = xlsheet1.getRange("A"+i, "D" + i).get_Value(null);
    xlsheet2.getRange("A"+curRow, "D" + curRow).set_Value(null, toCopy);
    curRow++;
}
xlwb.Save();                
于 2012-10-30T16:10:36.873 回答
0

如果您找不到“移动”数据的方法,请手动移动它:

  1. 将值复制到
  2. 确保副本有效
  3. 使原始单元格空白
  4. 节省
于 2012-10-30T15:02:43.147 回答