在两个不同的DataGridViews之间复制粘贴 [英] Copy paste between 2 different DataGridViews

查看:90
本文介绍了在两个不同的DataGridViews之间复制粘贴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,可以在CSV文件中导入并显示到datagridview。然后我创建了另一个datagridview以显示在搜索的输出上。这些都很有效。但是,我希望能够从
datagridview复制单元格,行,列或表,然后将数据粘贴到其他程序,如XLS,记事本,Word等。

I have created a program to import in a CSV file and display to datagridview. Then I created another datagridview to display on output of a search. Both these work VERY will. However, I want to be able to copy either cell, row, column, or table from the datagridview, and then paste data into some other program like XLS, Notepad, Word, etc.

我用单一方法做了这个,但不知道怎么告诉C#程序选择合适的对象。

I have done this with single, but not sure how to tell the C# program to select the appropriate object.

推荐答案

嗨John,

实际上,您可以将datagridview导出到Excel或PDF或其他file:

In fact, you can export the datagridview to Excel or PDF or other file:

    public partial class FrmDgvExport : Form
    {
        public FrmDgvExport()
        {
            InitializeComponent();
        }

        private void FrmDgvExport_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("1");
            dt.Columns.Add("2");
            dt.Columns.Add("3");
            dt.Columns.Add("4");
            dt.Rows.Add("A", "AA", "5000", "5000");
            dt.Rows.Add("A", "AAA", "5000", "5000");
            dt.Rows.Add("B", "BB", "5000", "5000");
            dt.Rows.Add("B", "BBB", "5000", "5000");
            dt.Rows.Add("C", "CC", "5000", "5000");

            this.dataGridView1.DataSource = dt;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string str = "MyDgv";
            ExportExcel(str, dataGridView1);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ExportPDF();
        }

        public static void ExportExcel(string fileName, DataGridView myDGV)
        {
            if (myDGV.Rows.Count > 0)
            {
                string saveFileName = "";
                SaveFileDialog saveDialog = new SaveFileDialog();
                saveDialog.DefaultExt = "xls";
                saveDialog.Filter = "Excel File|*.xls";
                saveDialog.FileName = fileName;
                saveDialog.ShowDialog();
                saveFileName = saveDialog.FileName;
                if (saveFileName.IndexOf(":") < 0) return;
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (xlApp == null)
                {
                    MessageBox.Show("can not create excel, your PC may not install the excel");
                    return;
                }

                Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
                Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
                Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//get sheet1  

                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
                }

                for (int r = 0; r < myDGV.Rows.Count; r++)
                {
                    for (int i = 0; i < myDGV.ColumnCount; i++)
                    {
                        worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                    }
                    Application.DoEvents();
                }
                worksheet.Columns.EntireColumn.AutoFit();

                if (saveFileName != "")
                {
                    try
                    {
                        workbook.Saved = true;
                        workbook.SaveCopyAs(saveFileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("export error, the file may be opened now\n" + ex.Message);
                    }

                }
                xlApp.Quit();
                GC.Collect();
                MessageBox.Show(fileName + "save successful", "prompt", MessageBoxButtons.OK);
            }
            else
            {
                MessageBox.Show("the datagridview is empty", "prompt", MessageBoxButtons.OK);
            }
        }

        public void ExportPDF()
        {
            //Creating iTextSharp Table from the DataTable data
            PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
            pdfTable.DefaultCell.Padding = 3;
            pdfTable.WidthPercentage = 30;
            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTable.DefaultCell.BorderWidth = 1;

            //Adding Header row
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                pdfTable.AddCell(cell);
            }

            int row = dataGridView1.Rows.Count;
            int cell2 = dataGridView1.Rows[1].Cells.Count;
            for (int i = 0; i < row - 1; i++)
            {
                for (int j = 0; j < cell2; j++)
                {
                    if (dataGridView1.Rows[i].Cells[j].Value == null)
                    {
                        //return directly
                        //return;
                        //or set a value for the empty data
                        dataGridView1.Rows[i].Cells[j].Value = "null";
                    }
                    pdfTable.AddCell(dataGridView1.Rows[i].Cells[j].Value.ToString());
                }
            }

            //Exporting to PDF
            string folderPath = @"C:\Users\[user]\Desktop\New folder\New folder\";
            if (!Directory.Exists(folderPath))
            {
                Directory.CreateDirectory(folderPath);
            }
            using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                stream.Close();
            }
            MessageBox.Show("Done");
        }
    }

问候,

Frankie


这篇关于在两个不同的DataGridViews之间复制粘贴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆