2011-09-01 100 views
1

問題出在這裏,我有幾個生成的excel文件,每個文件都有1個選項卡(但這並不是說未來將不會有更多)。將多個excel文件合併爲一個

我需要寫的是一個過程,可以打開每個文件,並將其所有工作表(選項卡)複製到一個新文件中。

最後,這個新文件應該包含所有其他文件的工作表。

目前,我已經創建了以下來完成excel格式之間的轉換。

我不太確定從這裏走到哪裏,我沒有任何我曾經創建過的源......並且不太清楚對象模型(爲了將製表符複製到一個新文件)或我將面對的問題,並確保我保持一切清理。

 object excelApplication = null; 
     object workbook = null; 
     object workbooks = null; 

     try 
     { 
      // Get the Remote Type 
      var excelType = Type.GetTypeFromProgID("Excel.Application", Properties.Settings.Default.ExcelServer, true); 

      // Instantiate the type 
      excelApplication = Activator.CreateInstance(excelType); 

      // Turn off Prompts 
      excelApplication.GetType().InvokeMember(
       "DisplayAlerts", 
       BindingFlags.SetProperty, 
       null, 
       excelApplication, 
       new Object[] { false }); 

      // Get a reference to the workbooks object 
      workbooks = excelApplication.GetType().InvokeMember(
       "Workbooks", 
       BindingFlags.GetProperty, 
       null, 
       excelApplication, 
       null); 

      // Open the input file 
      workbook = workbooks.GetType().InvokeMember(
       "Open", 
       BindingFlags.InvokeMethod, 
       null, 
       workbooks, 
       new object[] { inputFilePath }); 

      // If overwrite is turned off, and the file exist, the save as line will throw an error 
      if (File.Exists(outputFilePath) && overwriteIfExists) 
      { 
       File.Delete(outputFilePath); 
      } 

      // Save the workbook 
      workbook.GetType().InvokeMember(
       "SaveAs", 
       BindingFlags.InvokeMethod, 
       null, 
       workbook, 
       new object[] { outputFilePath, saveAsFileFormat, null, null, null, null, 1, null, null, null, null, null }); 
     } 
     finally 
     { 
      // Cleanup all created COM objects 
      if (workbook != null) 
      { 
       workbook.GetType().InvokeMember(
        "Close", 
        BindingFlags.InvokeMethod, 
        null, 
        workbook, 
        null); 
       Marshal.ReleaseComObject(workbook); 
       workbook = null; 
      } 

      if (workbooks != null) 
      { 
       Marshal.ReleaseComObject(workbooks); 
       workbooks = null; 
      } 

      if (excelApplication != null) 
      { 
       excelApplication.GetType().InvokeMember(
        "Quit", 
        BindingFlags.InvokeMethod, 
        null, 
        excelApplication, 
        null); 
       Marshal.ReleaseComObject(excelApplication); 
       excelApplication = null; 
      } 
     } 

編輯:此代碼幾乎工作,問題是應該實際執行復制的行...

public byte[] MergeFiles(FileFormat saveAsFileFormat, List<byte[]> inputFileBytesList) 
    { 
     var outputFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, Guid.NewGuid() + ".target.xls"); 

     Impersonate(
      Properties.Settings.Default.ImpersonationUser.Decrypt(), 
      Properties.Settings.Default.ImpersonationDomain, 
      Properties.Settings.Default.ImpersonationPassword.Decrypt() 
     ); 

     var convertedFileList = new List<string>(); 
     foreach (var inputFileBytes in inputFileBytesList) 
     { 
      var inputFileExtension = GetExtension(inputFileBytes); 
      var inputFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, Guid.NewGuid() + inputFileExtension); 
      var convertedFileBytes = SaveAs(saveAsFileFormat, inputFileBytes); 
      File.WriteAllBytes(inputFilePath, convertedFileBytes); 
      convertedFileList.Add(inputFilePath); 
     } 

     // Target Excel File 
     object targetExcelApplication = null; 
     object targetWorkbook = null; 
     object targetWorkbooks = null; 
     object targetWorksheets = null; 
     object targetWorksheet = null; 

     try 
     { 
      // Get the Remote Type 
      var excelType = Type.GetTypeFromProgID("Excel.Application", Properties.Settings.Default.ExcelServer, true); 

      // Instantiate the type 
      targetExcelApplication = Activator.CreateInstance(excelType); 

      // Turn off Prompts 
      targetExcelApplication.GetType().InvokeMember(
       "DisplayAlerts", 
       BindingFlags.SetProperty, 
       null, 
       targetExcelApplication, 
       new Object[] { false }); 

      // Get a reference to the workbooks object 
      targetWorkbooks = targetExcelApplication.GetType().InvokeMember(
       "Workbooks", 
       BindingFlags.GetProperty, 
       null, 
       targetExcelApplication, 
       null); 

      // Create a workbook to add the sheets to 
      targetWorkbook = targetWorkbooks.GetType().InvokeMember(
       "Add", 
       BindingFlags.InvokeMethod, 
       null, 
       targetWorkbooks, 
       new object[] { 1 }); 

      // Get a reference to the worksheets object 
      targetWorksheets = targetWorkbook.GetType().InvokeMember(
       "Sheets", 
       BindingFlags.GetProperty, 
       null, 
       targetExcelApplication, 
       null 
       ); 

      foreach (var inputFilePath in convertedFileList) 
      { 
       // Open each File, grabbing all tabs 
       object sourceExcelApplication = null; 
       object sourceWorkbooks = null; 
       object sourceWorkbook = null; 
       object sourceWorksheets = null; 

       try 
       { 
        // Instantiate the type 
        sourceExcelApplication = Activator.CreateInstance(excelType); 

        // Turn off Prompts 
        sourceExcelApplication.GetType().InvokeMember(
         "DisplayAlerts", 
         BindingFlags.SetProperty, 
         null, 
         sourceExcelApplication, 
         new Object[] {false}); 

        // Get a reference to the workbooks object 
        sourceWorkbooks = sourceExcelApplication.GetType().InvokeMember(
         "Workbooks", 
         BindingFlags.GetProperty, 
         null, 
         sourceExcelApplication, 
         null); 

        // Open the input file 
        sourceWorkbook = sourceWorkbooks.GetType().InvokeMember(
         "Open", 
         BindingFlags.InvokeMethod, 
         null, 
         sourceWorkbooks, 
         new object[] {inputFilePath}); 

        // Get a reference to the worksheets object 
        sourceWorksheets = sourceWorkbook.GetType().InvokeMember(
         "Sheets", 
         BindingFlags.GetProperty, 
         null, 
         sourceExcelApplication, 
         null); 

        var sourceSheetCount = (int)(sourceWorksheets.GetType().InvokeMember(
         "Count", 
         BindingFlags.GetProperty, 
         null, 
         sourceWorksheets, 
         null)); 

        for (var i = 1; i <= sourceSheetCount; i++) 
        { 
         var targetSheetCount = (int)(targetWorksheets.GetType().InvokeMember(
          "Count", 
          BindingFlags.GetProperty, 
          null, 
          targetWorksheets, 
          null)); 

         var sourceWorksheet = sourceWorksheets.GetType().InvokeMember(
          "Item", 
          BindingFlags.GetProperty, 
          null, 
          sourceWorksheets, 
          new Object[] { i }); 

         targetWorksheet = targetWorksheets.GetType().InvokeMember(
          "Item", 
          BindingFlags.GetProperty, 
          null, 
          targetWorksheets, 
          new Object[] { targetSheetCount }); 

         // TODO: Copy into target file 

         sourceWorksheet.GetType().InvokeMember(
          "Copy", 
          BindingFlags.InvokeMethod, 
          null, 
          sourceWorksheet, 
          new[] { Type.Missing, targetWorksheet } 
          ); 

         if (sourceWorksheet != null) 
         { 
          Marshal.ReleaseComObject(sourceWorksheet); 
          sourceWorksheet = null; 
         } 
        } 
       } 
       finally 
       { 
        // Cleanup all created COM objects 
        if (sourceWorksheets != null) 
        { 
         Marshal.ReleaseComObject(sourceWorksheets); 
         sourceWorksheets = null; 
        } 

        if (sourceWorkbook != null) 
        { 
         sourceWorkbook.GetType().InvokeMember(
          "Close", 
          BindingFlags.InvokeMethod, 
          null, 
          sourceWorkbook, 
          null); 
         Marshal.ReleaseComObject(sourceWorkbook); 
         sourceWorkbook = null; 
        } 

        if (sourceWorkbooks != null) 
        { 
         Marshal.ReleaseComObject(sourceWorkbooks); 
         sourceWorkbooks = null; 
        } 

        if (sourceExcelApplication != null) 
        { 
         sourceExcelApplication.GetType().InvokeMember(
          "Quit", 
          BindingFlags.InvokeMethod, 
          null, 
          sourceExcelApplication, 
          null); 
         Marshal.ReleaseComObject(sourceExcelApplication); 
         sourceExcelApplication = null; 
        } 
       } 
      } 

      // If overwrite is turned off, and the file exist, the save as line will throw an error 
      if (File.Exists(outputFilePath)) 
      { 
       File.Delete(outputFilePath); 
      } 

      // Save the workbook 
      targetWorkbook.GetType().InvokeMember(
       "SaveAs", 
       BindingFlags.InvokeMethod, 
       null, 
       targetWorkbook, 
       new object[] { outputFilePath, saveAsFileFormat, null, null, null, null, 1, null, null, null, null, null }); 
     } 
     finally 
     { 
      // Cleanup all created COM objects 
      if (targetWorksheets != null) 
      { 
       Marshal.ReleaseComObject(targetWorksheets); 
       targetWorksheets = null; 
      } 

      if (targetWorkbook != null) 
      { 
       targetWorkbook.GetType().InvokeMember(
        "Close", 
        BindingFlags.InvokeMethod, 
        null, 
        targetWorkbook, 
        null); 
       Marshal.ReleaseComObject(targetWorkbook); 
       targetWorkbook = null; 
      } 

      if (targetWorkbooks != null) 
      { 
       Marshal.ReleaseComObject(targetWorkbooks); 
       targetWorkbooks = null; 
      } 

      if (targetExcelApplication != null) 
      { 
       targetExcelApplication.GetType().InvokeMember(
        "Quit", 
        BindingFlags.InvokeMethod, 
        null, 
        targetExcelApplication, 
        null); 
       Marshal.ReleaseComObject(targetExcelApplication); 
       targetExcelApplication = null; 
      } 
     } 

     // Read target file bytes 
     var resultBytes = (File.Exists(outputFilePath)) 
      ? File.ReadAllBytes(outputFilePath) 
      : new byte[] { }; 

     // Delete working files 
     if (File.Exists(outputFilePath)) 
      File.Delete(outputFilePath); 
     foreach (var inputFilePath in convertedFileList.Where(File.Exists)) 
     { 
      File.Delete(inputFilePath); 
     } 

     Repersonate(); 

     // Return result 
     return resultBytes; 
    } 

我得到的錯誤System.Runtime.InteropServices.COMException: Worksheet類的複製方法失敗,這並沒有多大幫助...我不知道它爲什麼失敗...

+0

可能重複前加少許清理刪除被最初創建空白工作表到一個](http://stackoverflow.com/questions/830841/merge-excel-files-into-one) –

+0

@Davide Piras,我沒有使用互操作庫,也沒有一個工具。我需要以我目前用來轉換文件類型的相同方式來完成此操作。 – CaffGeek

+0

什麼類型的對象是excel應用程序?對我來說,它看起來像互操作庫...對此感到抱歉。 –

回答

2

這似乎是工作,剛需,然後在文件中活躍在第一片保存[合併Excel文件的

[WebMethod] 
    public byte[] MergeFiles(FileFormat saveAsFileFormat, List<byte[]> inputFileBytesList) 
    { 
     //var outputFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, Guid.NewGuid() + ".xls"); 
     var outputFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, "target.xls"); 

     Impersonate(
      Properties.Settings.Default.ImpersonationUser.Decrypt(), 
      Properties.Settings.Default.ImpersonationDomain, 
      Properties.Settings.Default.ImpersonationPassword.Decrypt() 
     ); 

     var convertedFileList = new List<string>(); 
     foreach (var inputFileBytes in inputFileBytesList) 
     { 
      var inputFileExtension = GetExtension(inputFileBytes); 
      var inputFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, Guid.NewGuid() + inputFileExtension); 
      File.WriteAllBytes(inputFilePath, inputFileBytes); 

      var convertedFilePath = Path.Combine(Properties.Settings.Default.WorkingFolder, Guid.NewGuid() + inputFileExtension); 
      SaveAsInternal(saveAsFileFormat, inputFilePath, convertedFilePath, true); 
      convertedFileList.Add(convertedFilePath); 
     } 

     // Target Excel File 
     object excelApplication = null; 
     object excelWorkbooks = null; 
     object targetWorkbook = null; 
     object targetWorksheets = null; 
     object targetWorksheet = null; 

     try 
     { 
      // Get the Remote Type 
      var excelType = Type.GetTypeFromProgID("Excel.Application", Properties.Settings.Default.ExcelServer, true); 

      // Instantiate the type 
      excelApplication = Activator.CreateInstance(excelType); 

      // Turn off Prompts 
      excelApplication.GetType().InvokeMember(
       "DisplayAlerts", 
       BindingFlags.SetProperty, 
       null, 
       excelApplication, 
       new Object[] { false }); 

      // Get a reference to the workbooks object 
      excelWorkbooks = excelApplication.GetType().InvokeMember(
       "Workbooks", 
       BindingFlags.GetProperty, 
       null, 
       excelApplication, 
       null); 

      // Create a workbook to add the sheets to 
      targetWorkbook = excelWorkbooks.GetType().InvokeMember(
       "Add", 
       BindingFlags.InvokeMethod, 
       null, 
       excelWorkbooks, 
       new object[] { 1 }); 

      // Get a reference to the worksheets object 
      targetWorksheets = targetWorkbook.GetType().InvokeMember(
       "Sheets", 
       BindingFlags.GetProperty, 
       null, 
       excelApplication, 
       null 
       ); 

      // Open each File, grabbing all tabs 
      foreach (var inputFilePath in convertedFileList) 
      { 
       object sourceWorkbook = null; 
       object sourceWorksheets = null; 

       try 
       { 
        // Open the input file 
        sourceWorkbook = excelWorkbooks.GetType().InvokeMember(
         "Open", 
         BindingFlags.InvokeMethod, 
         null, 
         excelWorkbooks, 
         new object[] {inputFilePath}); 

        // Get a reference to the worksheets object 
        sourceWorksheets = sourceWorkbook.GetType().InvokeMember(
         "Sheets", 
         BindingFlags.GetProperty, 
         null, 
         excelApplication, 
         null); 

        var sourceSheetCount = (int)(sourceWorksheets.GetType().InvokeMember(
         "Count", 
         BindingFlags.GetProperty, 
         null, 
         sourceWorksheets, 
         null)); 

        for (var i = 1; i <= sourceSheetCount; i++) 
        { 
         var targetSheetCount = (int)(targetWorksheets.GetType().InvokeMember(
          "Count", 
          BindingFlags.GetProperty, 
          null, 
          targetWorksheets, 
          null)); 

         var sourceWorksheet = sourceWorksheets.GetType().InvokeMember(
          "Item", 
          BindingFlags.GetProperty, 
          null, 
          sourceWorksheets, 
          new Object[] { i }); 

         targetWorksheet = targetWorksheets.GetType().InvokeMember(
          "Item", 
          BindingFlags.GetProperty, 
          null, 
          targetWorksheets, 
          new Object[] { targetSheetCount }); 

         // TODO: Copy into target file 

         sourceWorksheet.GetType().InvokeMember(
          "Copy", 
          BindingFlags.InvokeMethod, 
          null, 
          sourceWorksheet, 
          new[] { Type.Missing, targetWorksheet } 
          ); 

         if (sourceWorksheet != null) 
         { 
          Marshal.ReleaseComObject(sourceWorksheet); 
          sourceWorksheet = null; 
         } 
        } 
       } 
       finally 
       { 
        // Cleanup all created COM objects 
        if (sourceWorksheets != null) 
        { 
         Marshal.ReleaseComObject(sourceWorksheets); 
         sourceWorksheets = null; 
        } 

        if (sourceWorkbook != null) 
        { 
         sourceWorkbook.GetType().InvokeMember(
          "Close", 
          BindingFlags.InvokeMethod, 
          null, 
          sourceWorkbook, 
          null); 
         Marshal.ReleaseComObject(sourceWorkbook); 
         sourceWorkbook = null; 
        } 
       } 
      } 

      // If overwrite is turned off, and the file exist, the save as line will throw an error 
      if (File.Exists(outputFilePath)) 
      { 
       File.Delete(outputFilePath); 
      } 

      // Save the workbook 
      targetWorkbook.GetType().InvokeMember(
       "SaveAs", 
       BindingFlags.InvokeMethod, 
       null, 
       targetWorkbook, 
       new object[] { outputFilePath, saveAsFileFormat, null, null, null, null, 1, null, null, null, null, null }); 
     } 
     finally 
     { 
      // Cleanup all created COM objects 
      if (targetWorksheets != null) 
      { 
       Marshal.ReleaseComObject(targetWorksheets); 
       targetWorksheets = null; 
      } 

      if (targetWorkbook != null) 
      { 
       targetWorkbook.GetType().InvokeMember(
        "Close", 
        BindingFlags.InvokeMethod, 
        null, 
        targetWorkbook, 
        null); 
       Marshal.ReleaseComObject(excelWorkbooks); 
       excelWorkbooks = null; 
      } 

      if (excelWorkbooks != null) 
      { 
       Marshal.ReleaseComObject(excelWorkbooks); 
       excelWorkbooks = null; 
      } 

      if (excelApplication != null) 
      { 
       excelApplication.GetType().InvokeMember(
        "Quit", 
        BindingFlags.InvokeMethod, 
        null, 
        excelApplication, 
        null); 
       Marshal.ReleaseComObject(excelApplication); 
       excelApplication = null; 
      } 
     } 

     // Read target file bytes 
     var resultBytes = (File.Exists(outputFilePath)) 
      ? File.ReadAllBytes(outputFilePath) 
      : new byte[] { }; 

     // Delete working files 
     if (File.Exists(outputFilePath)) 
      File.Delete(outputFilePath); 
     foreach (var inputFilePath in convertedFileList.Where(File.Exists)) 
     { 
      File.Delete(inputFilePath); 
     } 

     Repersonate(); 

     // Return result 
     return resultBytes; 
    } 
0

使用ADO連接選擇值並使用copyFromRecordset方法從範圍粘貼到其他工作簿中。

+0

這不起作用,我需要所有的格式,圖像等... – CaffGeek

相關問題