使用c#将工作簿1中一个工作表的单元格/单元格内容复制到工作簿2中的另一个现有工作表

时间:2015-03-13 18:49:07

标签: c# .net excel-interop

我有两个excel文件。由于源HTML包含大量表格,因此从Web中报废并存储为excel文件时,其中的信息会混乱。现在我想将sheet1中的一些选择(单元格内容)从workbook1复制到workbook2中sheet1中的另一个单元格。我写了一些东西,但这会将同一张纸上的细胞复制到自身。

        //Check to see if path exists
        if (!File.Exists(path1))
        {
            //if file does not exist, 

            MessageBox.Show("File does not exixt.");
        }
        //if exists, it will open the file to write to it
        else
        {
            workBook1 = exlApp.Workbooks.Open(path1, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
                false, 0, true, false, false);
        }

        workBook2 = exlApp.Workbooks.Open(path2, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
               false, 0, true, false, false);

        //Get the already existing sheets from worksheet1 and worksheet2
        workSheet1 = (Excel.Worksheet)exlApp.Worksheets.get_Item(1);
        workSheet2 = (Excel.Worksheet)exlApp.Worksheets.get_Item(1);

        //Get the cell to copy the contents from 
        Excel.Range sourceRange = workSheet1.get_Range("A1");

        //Get the destination cell(in a different workbook) to copy
        Excel.Range destinationRange = workSheet2.get_Range("B2");

        sourceRange.Copy(Type.Missing);
        destinationRange.PasteSpecial(Excel.XlPasteType.xlPasteFormulas, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, false, false);

我尝试了几种方法,但有时会显示COM运行时错误或将内容复制到自身。有谁有想法吗?谢谢你的时间!

2 个答案:

答案 0 :(得分:0)

您似乎将相同的工作表分配给两个不同的变量:

//Get the already existing sheets from worksheet1 and worksheet2
workSheet1 = (Excel.Worksheet)exlApp.Worksheets.get_Item(1);
workSheet2 = (Excel.Worksheet)exlApp.Worksheets.get_Item(1);

两行中的get_Item(1)。

答案 1 :(得分:0)

这是一个简单的解决方案。下面是修复它的代码。

 //Check to see if path exists
        if (!File.Exists(path1))
        {
            //if file does not exist, 

            MessageBox.Show("File does not exixt.");
        }
        //if exists, it will open the file to write to it
        else
        {
            workBook1 = exlApp.Workbooks.Open(path1, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
                false, 0, true, false, false);
        }

        workBook2 = exlApp.Workbooks.Open(path2, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
               false, 0, true, false, false);




        //Get the cell to copy the contents from 
        Excel.Range sourceRange = workBook1.Sheets[1].Range("A1");

        //Get the destination cell(in a different workbook) to copy
        Excel.Range destinationRange = workBook2.Sheets[1].Range("B2");

        sourceRange.Copy(destinationRange);