我如何合并2个Excel文件到一个Excel文件与分离的表

本文关键字:文件 Excel 一个 分离 何合并 合并 2个 | 更新日期: 2023-09-27 18:07:05

我有两个Excel文件,我想把它们合并成一个单独的表格文件。

我试图执行合并与Microsoft.Office.Interop.Excel,但我不知道怎么用?

为·:

这里的方法获取一个范围,我想把它们合并到不同的文件:

internal object[,] GetValues(string filename)
    {
        object[,] values = new object[0, 0];
        try
        {
            Workbook workBook = _excelApp.Workbooks.Open(filename,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                Type.Missing, Type.Missing);
            values = ExcelScanIntenal(workBook);
            workBook.Close(false, filename, null);
            Marshal.ReleaseComObject(workBook);
        }
        catch
        {
        }
        return values;
    }
    private object[,] ExcelScanIntenal(Workbook workBookIn)
    {
        object[,] valueArray = new object[0, 0];
        Worksheet sheet = (Worksheet)workBookIn.Sheets[1];
        Range excelRange = sheet.UsedRange;
        valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
        return valueArray;
    }

这里我想合并这些值:

   internal void AddWorksheetToExcelWorkbook(string filename, string worksheetName, object[,] valueArray)
    {
        Microsoft.Office.Interop.Excel.Application xlApp = null;
        Workbook xlWorkbook = null;
        Sheets xlSheets = null;
        Worksheet xlNewSheet = null;
        try
        {
            xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
                return;
            xlWorkbook = xlApp.Workbooks.Open(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            xlSheets = xlWorkbook.Sheets as Sheets;
            xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
            xlNewSheet.Name = worksheetName;
            xlWorkbook.Save();
            xlWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
            xlApp.Quit();
        }
        finally
        {
            Marshal.ReleaseComObject(xlNewSheet);
            Marshal.ReleaseComObject(xlSheets);
            Marshal.ReleaseComObject(xlWorkbook);
            Marshal.ReleaseComObject(xlApp);
            xlApp = null;
        }
    }

的问题是,xlNewSheet是没有任何属性,可以得到的值。我怎么添加??

我如何合并2个Excel文件到一个Excel文件与分离的表

不太确定问题是什么…但要以编程方式合并excel文件,请参见以下起始点:

  • http://www.dotnetspider.com/forum/242869-How-merge-two-excel-sheets-c.aspx
  • http://www.dotnetperls.com/excel

如果你需要更多的信息,请显示一些代码,并告诉什么是不工作…

编辑-按注释:

您可以使用xlNewSheet.Cells来获得一个范围,并使用其Columns/Rows/Item属性更改/添加任何您想要的值-即在您的情况下,从valueArray