拆分Excel选项卡以分隔文件

时间:2017-12-11 19:23:33

标签: c# .net excel

我尝试编写C#.NET函数将Excel工作表拆分为单独的文件。我使用的是Excel Interop,但我似乎无法按照自己的意愿使用它。我能做的最好的事情是使用选中的特定选项卡重新保存文件。 MSDN文档似乎很不清楚使用哪些函数。我读到其他地方,其中一些功能并没有像预期的那样表现出来。

               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 :(得分:1)

我完全修改了你的代码。我想说几点:

  1. 在您的用户界面中,您必须设置其中一个Radiobuttons,这样您就不必在代码中写入错误检测输出格式,即必须始终设置输出格式。
  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!");
    
    }
    
相关问题