使用C#将选定列的所有行从一个Excel文件复制到另一个Excel文件可以通过以下步骤实现:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application excelApp = new Excel.Application();
Excel.Workbook sourceWorkbook = excelApp.Workbooks.Open("源文件路径");
Excel.Workbook targetWorkbook = excelApp.Workbooks.Open("目标文件路径");
Excel.Worksheet sourceWorksheet = sourceWorkbook.Worksheets["工作表名称"];
Excel.Worksheet targetWorksheet = targetWorkbook.Worksheets["工作表名称"];
Excel.Range sourceRange = sourceWorksheet.Range["选定列的范围"];
Excel.Range sourceData = sourceRange.EntireRow;
sourceData.Copy(Type.Missing);
Excel.Range targetRange = targetWorksheet.Cells[targetWorksheet.UsedRange.Rows.Count + 1, 1];
targetWorksheet.Paste(targetRange, Type.Missing);
targetWorkbook.Save();
excelApp.Quit();
完整的代码示例:
using Excel = Microsoft.Office.Interop.Excel;
class Program
{
static void Main(string[] args)
{
Excel.Application excelApp = new Excel.Application();
Excel.Workbook sourceWorkbook = excelApp.Workbooks.Open("源文件路径");
Excel.Workbook targetWorkbook = excelApp.Workbooks.Open("目标文件路径");
Excel.Worksheet sourceWorksheet = sourceWorkbook.Worksheets["工作表名称"];
Excel.Worksheet targetWorksheet = targetWorkbook.Worksheets["工作表名称"];
Excel.Range sourceRange = sourceWorksheet.Range["选定列的范围"];
Excel.Range sourceData = sourceRange.EntireRow;
sourceData.Copy(Type.Missing);
Excel.Range targetRange = targetWorksheet.Cells[targetWorksheet.UsedRange.Rows.Count + 1, 1];
targetWorksheet.Paste(targetRange, Type.Missing);
targetWorkbook.Save();
excelApp.Quit();
}
}
注意:在使用此代码之前,需要确保已安装Microsoft Office并引用了Microsoft.Office.Interop.Excel组件。
领取专属 10元无门槛券
手把手带您无忧上云