我通过c#将内容写入excel文件。我在Excel中有4列和多行。当应用程序运行时,我需要检查sheet1中是否存在数据,然后它应该移动到sheet2。如果sheet2也包含数据,则应附加sheet2数据。我正在使用interop 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();
}
答案 0 :(得分: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();
答案 1 :(得分:0)
如果你找不到一种方法来移动&#34;数据,手动移动: