2017-12-11 24 views
-1

Excelワークシートを別々のファイルに分割するC#.NET関数を作成しようとしています。私はExcel Interopを使用していますが、私が望むように動作させることはできません。私ができることは、特定のタブを選択してファイルを再保存することです。 MSDNのドキュメントは、どの機能を使用するかについては非常に不明瞭です。私は、これらの機能のいくつかが期待どおりに動作していないことを他の場所で読んでいます。Excelタブを分割してファイルを分割する

   private void SplitFile(string targetPath, string sourceFile) 
    { 
     Excel.Application xlApp; 
     Excel.Workbook xlFile; 
     //Excel.Worksheet xlWorkSheet; 
     object misValue = System.Reflection.Missing.Value; 

     string exportFormat = ""; 
     if (cboExcel.Checked == true) //set the output format 
      exportFormat = "XLSX"; 
     else if (cboCsv.Checked == true) 
      exportFormat = "CSV"; 
     else 
      Console.WriteLine("Error detecting output format"); 

     xlApp = new Excel.Application(); //object for controlling Excel 
     xlFile = xlApp.Workbooks.Open(txtFilePath.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); //open the source file 
     //xlWorkSheet = (Excel.Worksheet)xlFile.Worksheets.get_Item(1); //Select the first tab in the file. Note: Index does NOT start are zero. 


     xlApp.DisplayAlerts = false; //override Excel save dialog message 
     int TabCount = xlFile.Worksheets.Count; //total count of the tabs in the file 

     int sheetCount = 0; //this will be used to output the number of exported sheets 
     for (int i = 1; i <= TabCount; i++) //for each sheet in the workbook... 
     { 
      //Console.WriteLine(i.ToString() + ": " + xlFile.Worksheets.Item[i].Name); 
      xlApp.ActiveWorkbook.Sheets[i].Select(); 
      string sheetName = xlFile.Sheets[i].Name; //..get the name of the sheet. It will be used for the new filename 

      Console.WriteLine(i.ToString() + ": " + sheetName); 
      string newFilename = targetPath + "\\" + sheetName; //set the filename with full path, but no extension 
      Console.WriteLine(newFilename); 

      toolStripStatus.Text = "Exporting: " + sheetName; //update the status bar 
      Excel.Worksheet tempSheet = (xlApp.Worksheets[i]); //Current tab will be saved to this in a new workbook 
      tempSheet.Copy(); 
      Excel.Workbook tempBook = xlApp.ActiveWorkbook; 

      try 
      { 
       switch (exportFormat) //if the file does NOT exist OR if does and the the user wants to overwrite it, do the export and increase the sheetCount by 1 
       { 
        case "CSV": 
         if (!File.Exists(newFilename + ".csv") || MessageBox.Show(sheetName + ".csv already exists. Overwrite?", "Confirm Overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) 
         { 
          tempBook.Worksheets[1].SaveAs(newFilename, Excel.XlFileFormat.xlCSV, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing); 
          sheetCount++; 
         } 
         break; 
        case "XLSX": 
         if (!File.Exists(newFilename + ".xlsx") || MessageBox.Show(sheetName + ".xlsx already exists. Overwrite?", "Confirm Overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) 
         { 
          tempBook.Worksheets[1].SaveAs(newFilename, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing); 
          //tempSheet.SaveAs(newFilename, Excel.XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing); 
          sheetCount++; 
         } 
         break; 
        default: 
         Console.WriteLine("Unexpected export format"); 
         MessageBox.Show("Unexpected export format"); 
         break; 
       } 
      } 
      catch (Exception ex) 
      { 
       toolStripStatus.Text = "Error!"; 

       string errorMessage = "Error Exporting " + sheetName + System.Environment.NewLine + "Original Message: " + ex.Message; 
       MessageBox.Show(errorMessage, "Error Exporting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
       Console.WriteLine(errorMessage); 
       toolStripStatus.Text = "Ready"; 

       break; 
      } 
     } 

     //Closing Processes Start =================================================== 
     toolStripStatus.Text = "Process Finished"; 
     xlApp.DisplayAlerts = true; 
     xlFile.Close(true, misValue, misValue); 
     xlApp.Quit(); 
     Console.WriteLine(sheetCount.ToString() + " files exported."); 
     MessageBox.Show(sheetCount.ToString() + " files exported.","Process Complete", MessageBoxButtons.OK ,MessageBoxIcon.Information); 
     toolStripStatus.Text = "Ready"; 
     //Closing Processes Finish ==================================================================================================== 

ターゲットファイルをファイルごとに複数のファイルに分割すると予想されます。

上記のコードを使用すると、選択したタブだけで同じファイルコピーを取得できます。私はそれ以来、上記のバリエーションをいくつか試しましたが、何もうまくいきません。

+1

あなたはより多くの情報を提供する必要があります。あなたが今やっていること、そしてうまくいかないこと(あなたが期待している結果と比べて得られる結果)を見せてください。 –

答えて

0

コードを完全に改訂しました。出力形式、つまり、あなたのUIで

  1. あなたはエラーが出力形式を検出するように、あなたのコードで記述する必要がないように、あなたがチェックラジオボタンのいずれかを設定する必要があります。私は、いくつかのノートを与えるしたいのですが必ず設定する必要があります。
  2. sourceFileパラメータは何をするのか分かりませんでした。
  3. ファイルパスを扱うときは、常にパスを扱うための多くの便利なメソッドを持つSystem.IO.Path静的クラスを扱います。
  4. DRYに従ってください(ワークブックを保存するときに壊れます)。

    private void SplitFile(string targetPath, string sourceFile) 
    { 
    
        bool isSave; 
        Excel.XlFileFormat fileFormat = Excel.XlFileFormat.xlOpenXMLWorkbook; 
    
        string exportFormat = ""; 
        if (cboExcel.Checked) //set the output format 
         exportFormat = "XLSX"; 
        else if (cboCsv.Checked) 
         exportFormat = "CSV"; 
    
        Excel.Application xlApp = new Excel.Application(); //object for controlling Excel 
        Excel.Workbook xlFile = xlApp.Workbooks.Open(txtFilePath.Text); //open the source file 
    
        xlApp.DisplayAlerts = false; //override Excel save dialog message 
        int TabCount = xlFile.Worksheets.Count; //total count of the tabs in the file 
    
        int sheetCount = 0; //this will be used to output the number of exported sheets 
        for (int i = 1; i <= TabCount; i++) //for each sheet in the workbook... 
        { 
         isSave = true; //Must reset to true 
         string sheetName = xlFile.Sheets[i].Name; 
         string newFilename = System.IO.Path.Combine(targetPath, sheetName); //set the filename with full path, but no extension 
    
         toolStripStatus.Text = "Exporting: " + sheetName; //update the status bar 
         Excel.Worksheet tempSheet = xlApp.Worksheets[i]; //Current tab will be saved to this in a new workbook 
         tempSheet.Copy(); 
         Excel.Workbook tempBook = xlApp.ActiveWorkbook; 
    
         try 
         { 
          switch (exportFormat) //if the file does NOT exist OR if does and the the user wants to overwrite it, do the export and increase the sheetCount by 1 
          { 
           case "CSV": 
            newFilename += ".csv"; 
            fileFormat = Excel.XlFileFormat.xlCSV; 
            break; 
           case "XLSX": 
            newFilename += ".xlsx"; 
            fileFormat = Excel.XlFileFormat.xlOpenXMLWorkbook; 
            break; 
          } 
    
          if (File.Exists(newFilename)) 
           isSave = (MessageBox.Show(sheetName + ".xlsx already exists. Overwrite?", "Confirm Overwrite", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes); 
    
          if (isSave) 
          { 
           tempBook.SaveAs(newFilename, fileFormat); 
           tempBook.Close(false); 
           sheetCount++; 
          } 
    
         } 
         catch (Exception ex) 
         { 
          toolStripStatus.Text = "Error!"; 
          string errorMessage = "Error Exporting " + sheetName + System.Environment.NewLine + "Original Message: " + ex.Message; 
          MessageBox.Show(errorMessage, "Error Exporting", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
          toolStripStatus.Text = "Ready"; 
         } 
        } 
    
        xlFile.Close(false); 
        GC.Collect(); 
        GC.WaitForFullGCComplete(); 
        GC.Collect(); 
        GC.WaitForFullGCComplete(); 
    
        MessageBox.Show("Well done!"); 
    
    } 
    
+0

ありがとうございました。あなたの提案を実装しようとしましたが、一般的なエラー: 無効なインデックスに遭遇しました。 (HRESULTからの例外:0x800200B(DISP_E_BANDINDEX)) 編集:最初のタブを独自のファイルとして保存していたので、少なくとも進歩しました! 編集2:例外はtempSheet.Copy()で発生します。 – DarkWolff

+0

あなたが現在持っている実際のコードへのあなたの答えを更新して、私が調べることができるようにしてください。 – JohnyL

+0

コードが更新されました。ありがとう! – DarkWolff

関連する問題