如何将2个Excel文件合并为一个带有分隔表的Excel文件?

时间:2011-08-28 20:38:57

标签: c# excel

我有两个Excel文件,我想将它们合并到一个带有单独工作表的文件中。

我尝试与Microsoft.Office.Interop.Excel执行合并, 但我不明白如何使用它?

  

对于Yahia:

这里是获取我想要将它们与不同文件合并的范围的方法:

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没有任何可以获取值的属性..我该如何添加?

1 个答案:

答案 0 :(得分:1)

不确定问题是什么......但是以编程方式合并excel文件请参见起点:

如果您需要更多信息,请先显示一些代码,然后告诉我究竟什么不起作用......

编辑 - 根据评论:

您可以使用xlNewSheet.Cells获取范围,并使用其Columns / Rows / Item属性更改/添加您想要的任何值 - 例如,在您的情况下来自{ {1}} ...