如何使用C#和EPPlus库比较2个.xlsx文件?

时间:2014-08-26 09:39:07

标签: c# excel epplus

我正在努力使用提到的库比较2个.xlsx文件。我的目标是分别比较两个文件中的2列,如果单元格相互匹配,则执行一些工作。这是我的代码,它似乎不起作用。它有什么问题?

FileInfo plik1 = new FileInfo(file1);
        FileInfo plik2 = new FileInfo(file2);

        using (ExcelPackage xlPackage2 = new ExcelPackage(plik2))
        {
            var worksheet2 = xlPackage2.Workbook.Worksheets[1];

            //var start = worksheet.Dimension.Start;
            //var end = worksheet.Dimension.End;
            //var col = worksheet.Column(1);

            using (ExcelPackage xlPackage = new ExcelPackage(plik1))
            {
                var worksheet = xlPackage.Workbook.Worksheets[1];

                int j = 0;
                    for (j=1; j<2500000; j++)
                    {
                        if (worksheet.Cells[j, 1].Value == worksheet2.Cells[j, 2].Value)
                        {

                            worksheet.Cells[j, 13].Value = worksheet2.Cells[j, 14].Value;
                            worksheet.Cells[j, 14].Value = worksheet2.Cells[j, 16].Value;

                        }

                    }

                string path = "C:\\Users\\bddddz\\Desktop\\asd\\final.xlsx";

                xlPackage.SaveAs(new FileInfo(path));


                xlPackage.Stream.Close();
                xlPackage2.Stream.Close();

            }
        }

1 个答案:

答案 0 :(得分:0)

为要保存的新文件使用单独的ExcelPackage。

    FileInfo plik1 = new FileInfo(file1);
    FileInfo plik2 = new FileInfo(file2);
    FileInfo path = new FileInfo("C:\\Users\\bddddz\\Desktop\\asd\\final.xlsx");

    using (ExcelPackage xlPackageNew = new ExcelPackage(path))
    using (ExcelPackage xlPackage = new ExcelPackage(plik1))
    using (ExcelPackage xlPackage2 = new ExcelPackage(plik2))
    {
        var worksheet2 = xlPackage2.Workbook.Worksheets[1];
        var worksheet = xlPackage.Workbook.Worksheets[1];
        var worksheet3 = xlPackageNew.Workbook.Worksheets.Add("new"); 

        int j = 0;
        for (j=1; j<2500000; j++)
        {
            if (worksheet.Cells[j, 1].Value == worksheet2.Cells[j, 2].Value)
            {
                worksheet3.Cells[j, 13].Value = worksheet2.Cells[j, 14].Value;
                worksheet3.Cells[j, 14].Value = worksheet2.Cells[j, 16].Value;
            }
        }

        xlPackageNew.Save();
    }