最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - Excel.Range.PasteSpecial fail - Stack Overflow

programmeradmin6浏览0评论

I have a program where I use multiple DataGridViews. These DataGrids contain hundreds of data entries that I need to transfer to an Excel file to create scatter plots. To achieve this, I thought the fastest way to transfer the tables to Excel was by using the Clipboard.

The code works relatively well the first time it runs. However, since the data in the tables may change due to structural analysis updates, this function can be executed multiple times. Occasionally, I encounter the following error:

System.Runtime.InteropServices.ExternalException (0x800401D0): Requested Clipboard operation did not succeed.

I would greatly appreciate any help in finding a solution to this issue.

    public void saveInteraction_Click(object sender, EventArgs e)
    {

        Process[] pp = Process.GetProcessesByName("excel");
        foreach (Process p in pp)
        {
            if (p.MainWindowTitle.Length == 0)
                p.Kill();
        }

        Excel.Application xlexcel;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
       
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        object misValue = System.Reflection.Missing.Value;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);            

        #region DIRECTORIO DE GUARDADO Y ELIMINACION DE ARCHIVOS
        string directoryPath = null;

        if (!System.IO.Directory.Exists($@"{Path.GetDirectoryName(FormPrincipal.Var.doc.PathName)}\6. Lift & Bracing\1. Reports\INTERACTIONS"))
        {
            System.IO.DirectoryInfo di = System.IO.Directory.CreateDirectory($@"{Path.GetDirectoryName(FormPrincipal.Var.doc.PathName)}\6. Lift & Bracing\1. Reports\INTERACTIONS");
        }

        if (System.IO.Directory.Exists($@"{Path.GetDirectoryName(FormPrincipal.Var.doc.PathName)}\6. Lift & Bracing\1. Reports\INTERACTIONS"))
        {
            directoryPath = $@"{Path.GetDirectoryName(FormPrincipal.Var.doc.PathName)}\6. Lift & Bracing\1. Reports\INTERACTIONS";
        }

        string baseFileName = $"{FormPrincipal.Var.form.PanelNameButton.Text}-Interactions";

        string pdfPath = Path.Combine(directoryPath, $"{baseFileName}.xlsx");

        if (File.Exists(pdfPath))
        {
            File.Delete(pdfPath);
        }
        #endregion

        int n = 1;
        if (FormPrincipal.Var.form.RowsBox.Text == "2")
        {
            n = 2;
        }
        if (FormPrincipal.Var.form.RowsBox.Text == "4")
        {
            n = 4;
        }
        try
        {
            for (int i = 0; i < n; i++)
            {
                copyAlltoClipboard(i);

                // Allow the clipboard to update.
                Application.DoEvents();
                Thread.Sleep(1000);

                Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, i * 6 + 2];                   

                CR.PasteSpecial(Excel.XlPasteType.xlPasteValues);
            }
            xlWorkSheet.Cells[1, 1].Value = "Tension Adm";
            xlWorkSheet.Cells[1, 2].Value = "Shear Adm";
            xlWorkSheet.Cells[2, 1].Value = tensionCap_textBox.Text;
            xlWorkSheet.Cells[91, 2].Value = shearCap_textBox.Text;

            xlWorkBook.SaveAs(pdfPath);
            xlWorkBook.Close(false);
            xlexcel.Quit();

        }
        catch (Exception exp)
        {
            MessageBox.Show($"{exp}");
            xlWorkBook.Close(false);
            xlexcel.Quit();
        }            
    }

    private void copyAlltoClipboard(int i)
    {
        DataObject dataObj1 = null;
        
        if (i == 0)
        {
            dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            dataGridView1.MultiSelect = true;
            dataGridView1.SelectAll();

            dataObj1 = dataGridView1.GetClipboardContent();
        }

        if (i == 1)
        {
            dataGridView2.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            dataGridView2.MultiSelect = true;
            dataGridView2.SelectAll();

            dataObj1 = dataGridView2.GetClipboardContent();
        }

        if (i == 2)
        {
            dataGridView3.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            dataGridView3.MultiSelect = true;
            dataGridView3.SelectAll();

            dataObj1 = dataGridView3.GetClipboardContent();
        }

        if (i == 3)
        {
            dataGridView4.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
            dataGridView4.MultiSelect = true;
            dataGridView4.SelectAll();

            dataObj1 = dataGridView4.GetClipboardContent();
        }
                                                                         

        if (dataObj1 != null)
            Clipboard.SetDataObject(dataObj1);            
    }

This is the code I use.

发布评论

评论列表(0)

  1. 暂无评论