我正在使用此代码,但是由于我想复制具有特定属性的整行,并且我不知道总行数。
Excel.Application excelApplication = new Excel.Application();
srcPath = "C:\\Users\\sn314708\\Desktop\\Excel\\1.xlsx";
Excel.Workbook srcworkBook = excelApplication.Workbooks.Open(srcPath);
Excel.Worksheet srcworkSheet = (Microsoft.Office.Interop.Excel.Worksheet)srcworkBook.Sheets.get_Item(1);
destPath = "C:\\Users\\sn314708\\Desktop\\Excel\\2.xlsx";
Excel.Workbook destworkBook = excelApplication.Workbooks.Open(destPath, 0, false);
Excel.Worksheet destworkSheet = (Microsoft.Office.Interop.Excel.Worksheet)destworkBook.Sheets.get_Item(1);
Excel.Range from = srcworkSheet.Range["A1:C100"];
Excel.Range to = destworkSheet.Range["A1:C100"];
from.Copy(to);
destworkBook.SaveAs("C:\\Users\\sn314708\\Desktop\\Excel\\2 " + DateTime.Now.ToString("MM_dd_yyyy") + ".xlsx");
您可以确定要复制的最大行数,也可以找到整个工作表中使用的最后一行(我认为这样更好)。您可以执行的示例:
int lastUsedRow = srcworkSheet.Cells.Find("*", System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value,
XlSearchOrder.xlByRows, XlSearchDirection.xlPrevious,
false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row;
int colIndex = 1;
for(int rowIndex = 1; rowIndex <= lastUsedRow; rowIndex++ )
{
destworkSheet.Cells[rowIndex, colIndex] = srcworkSheet.Cells[rowIndex, colIndex];
}
行和列的索引始终从1开始。