datagridview复制、剪切、粘贴、清空、增加行、删除行、增加列、删除列,导出Excel/Word

1.导入Excel。代码走先。

[csharp] view plain copy print ?
  1. public void ExcelToDataGridView(string filePath, DataGridView dataGridView1)  
  2.       {  
  3.           //根据路径打开一个Excel文件并将数据填充到DataSet中   
  4.           string strConn = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + filePath + "; Extended Properties = 'Excel 8.0;HDR =YES; IMEX=2'";  
  5.           // 导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入   
  6.           OleDbConnection conn = new OleDbConnection(strConn);  
  7.           conn.Open();  
  8.           string strExcel = "select * from [sheet1$]";  
  9.           OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);  
  10.           ds = new DataSet();  
  11.           myCommand.Fill(ds, "[Sheet1$]");  
  12.           dataGridView1.DataMember = "[Sheet1$]";  
  13.           dataGridView1.DataSource = ds;  
  14.           conn.Close();  
  15.           dataGridView1.AllowUserToAddRows = true;  
  16.           //禁用自动排序   
  17.           for (int k= 0;k < dataGridView1.Columns.Count; k++)  
  18.           {  
  19.               dataGridView1.Columns[k].SortMode = DataGridViewColumnSortMode.NotSortable;  
  20.           }  
  21.   
  22.           int cCount = dataGridView1.ColumnCount;  
  23.           int rCount = dataGridView1.RowCount;  
  24.           double[,] array = new double[rCount, cCount];  
  25.           for (int j = 0; j < rCount - 1; j++)                               // 逐行遍历   
  26.           {  
  27.               for (int i = 0; i < cCount - 1; i++)                          // 逐列遍历   
  28.               {  
  29.                   array[j, i] = Convert.ToDouble(dataGridView1.Rows[j].Cells[i].Value.ToString());  
  30.               }  
  31.           }  
  32.       }  
  public void ExcelToDataGridView(string filePath, DataGridView dataGridView1)
        {
            //根据路径打开一个Excel文件并将数据填充到DataSet中
            string strConn = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " + filePath + "; Extended Properties = 'Excel 8.0;HDR =YES; IMEX=2'";
            // 导入时包含Excel中的第一行数据,并且将数字和字符混合的单元格视为文本进行导入
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "select * from [sheet1$]";
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
            ds = new DataSet();
            myCommand.Fill(ds, "[Sheet1$]");
            dataGridView1.DataMember = "[Sheet1$]";
            dataGridView1.DataSource = ds;
            conn.Close();
            dataGridView1.AllowUserToAddRows = true;
            //禁用自动排序
            for (int k= 0;k < dataGridView1.Columns.Count; k++)
            {
                dataGridView1.Columns[k].SortMode = DataGridViewColumnSortMode.NotSortable;
            }

            int cCount = dataGridView1.ColumnCount;
            int rCount = dataGridView1.RowCount;
            double[,] array = new double[rCount, cCount];
            for (int j = 0; j < rCount - 1; j++)                               // 逐行遍历
            {
                for (int i = 0; i < cCount - 1; i++)                          // 逐列遍历
                {
                    array[j, i] = Convert.ToDouble(dataGridView1.Rows[j].Cells[i].Value.ToString());
                }
            }
        }
[csharp] view plain copy print ?
  1.   private void button1_Click(object sender, EventArgs e)  
  2.         {  
  3.             // 打开一个选择框   
  4.             OpenFileDialog ofd = new OpenFileDialog();  
  5.             ofd.Title = "Excel文件";  
  6.             ofd.FileName = "";  
  7.             ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  
  8.             ofd.Filter = "Excel文件(*.xls)|*.xls";  
  9.             ofd.ValidateNames = true;            // 文件有效性验证vValidateNames,验证用户输入的是否是一个有效的windows 文件名   
  10.             ofd.CheckFileExists = true;           // 验证文件的有效性   
  11.             ofd.CheckPathExists = true;        // 验证路径的有效性   
  12.             strName = string.Empty;  
  13.             if (ofd.ShowDialog() == DialogResult.OK)  
  14.             {  
  15.                 strName = ofd.FileName;  
  16.             }  
  17.             if (strName == "")  
  18.             {  
  19.                 MessageBox.Show("没有选择Excel文件!无法进行数据导入");  
  20.                 return;  
  21.             }  
  22.             DgvSet EtG = new DgvSet();  
  23.             EtG.ExcelToDataGridView(strName, this.dataGridView1);  
  24.         }  
  private void button1_Click(object sender, EventArgs e)
        {
            // 打开一个选择框
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Excel文件";
            ofd.FileName = "";
            ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            ofd.Filter = "Excel文件(*.xls)|*.xls";
            ofd.ValidateNames = true;            // 文件有效性验证vValidateNames,验证用户输入的是否是一个有效的windows 文件名
            ofd.CheckFileExists = true;           // 验证文件的有效性
            ofd.CheckPathExists = true;        // 验证路径的有效性
            strName = string.Empty;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                strName = ofd.FileName;
            }
            if (strName == "")
            {
                MessageBox.Show("没有选择Excel文件!无法进行数据导入");
                return;
            }
            DgvSet EtG = new DgvSet();
            EtG.ExcelToDataGridView(strName, this.dataGridView1);
        }

用此方法导入Excel最为方便,注意需要命名空间using System.Data.OleDb;


2.我遇到最大的难题就是插入行,因为此导入Excel方法会绑定数据源,当你用代码插入时总会提示“当控件与数据源绑定时,无法以编程方式向其中添加行”,最后得以高手帮助,搞定。见代码。

[csharp] view plain copy print ?
  1. public void AddExcelToDataGridView(DataGridView dataGridView1, int index)  
  2.        {  
  3.                dataGridView1.DataBindings.Clear();  
  4.                DataRow row = row = ds.Tables[0].NewRow();  
  5.                ds.Tables[0].Rows.InsertAt(row, index);  
  6.                dataGridView1.DataSource = ds;  
  7.                dataGridView1.AllowUserToAddRows = true;  
  8.        }  
 public void AddExcelToDataGridView(DataGridView dataGridView1, int index)
        {
                dataGridView1.DataBindings.Clear();
                DataRow row = row = ds.Tables[0].NewRow();
                ds.Tables[0].Rows.InsertAt(row, index);
                dataGridView1.DataSource = ds;
                dataGridView1.AllowUserToAddRows = true;
        }

[csharp] view plain copy print ?
  1. //datagridview右键功能   
  2.  private void 插入行ToolStripMenuItem_Click(object sender, EventArgs e)  
  3.         {  
  4.             try  
  5.             {  
  6.                 //MessageBox.Show(dataGridView1.CurrentRow.Index.ToString());   
  7.                 DgvSet EtG = new DgvSet();  
  8.                 EtG.AddExcelToDataGridView( this.dataGridView1,  dataGridView1.CurrentRow.Index);  
  9.                 //this.dataGridView1.Rows.Insert(dataGridView1.CurrentRow.Index, 1);   
  10.                 //this.dataGridView1.Rows.Insert(dataGridView1.CurrentRow.Index, new DataGridViewRow());   
  11.             }  
  12.             catch (Exception ex)  
  13.             {  
  14.                 MessageBox.Show(ex.Message.ToString());  
  15.             }  
  16.         }  
//datagridview右键功能
 private void 插入行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //MessageBox.Show(dataGridView1.CurrentRow.Index.ToString());
                DgvSet EtG = new DgvSet();
                EtG.AddExcelToDataGridView( this.dataGridView1,  dataGridView1.CurrentRow.Index);
                //this.dataGridView1.Rows.Insert(dataGridView1.CurrentRow.Index, 1);
                //this.dataGridView1.Rows.Insert(dataGridView1.CurrentRow.Index, new DataGridViewRow());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }


3.就是datagridview单元格为空问题,而datagridview单元格为空不能使用NULL,应使用DBNull.Value;如下:
[csharp] view plain copy print ?
  1. public void Clear(DataGridView dataGridView1)  
  2.       {  
  3.           foreach (DataGridViewCell cell in dataGridView1.SelectedCells)  
  4.           {  
  5.               cell.Value = DBNull.Value;  
  6.           }  
  7.       }  
  public void Clear(DataGridView dataGridView1)
        {
            foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
            {
                cell.Value = DBNull.Value;
            }
        }

4.另一个较复杂问题就是粘贴,,粘贴不仅要能够从外面的Excel复制在datagridview粘贴,本身datagridview还要能够复制粘贴,而且,当复制行列数超过datagridview总行列数时,datagridview还要能够自动增加行与列。代码

[csharp] view plain copy print ?
  1. #region 粘贴   
  2.         public int Paste(DataGridView dgv, string pasteText, int kind, bool b_cut)  
  3.         {  
  4.             try  
  5.             {  
  6.                 if (kind == 0)  
  7.                 {  
  8.                     pasteText = Clipboard.GetText();  
  9.                 }  
  10.                 if (string.IsNullOrEmpty(pasteText))  
  11.                     return -1;  
  12.                 int rowNum = 0;  
  13.                 int columnNum = 0;  
  14.                 //获得当前剪贴板内容的行、列数   
  15.                 for (int i = 0; i < pasteText.Length; i++)  
  16.                 {  
  17.                     if (pasteText.Substring(i, 1) == "\t")  
  18.                     {  
  19.                         columnNum++;  
  20.                     }  
  21.                     if (pasteText.Substring(i, 1) == "\n")  
  22.                     {  
  23.                         rowNum++;  
  24.                     }  
  25.                 }  
  26.                 Object[,] data;  
  27.                 //粘贴板上的数据来自于EXCEL时,每行末都有\n,在DATAGRIDVIEW内复制时,最后一行末没有\n   
  28.                 if (pasteText.Substring(pasteText.Length - 1, 1) == "\n")  
  29.                 {  
  30.                     rowNum = rowNum - 1;  
  31.                 }  
  32.                 columnNum = columnNum / (rowNum + 1);  
  33.                 data = new object[rowNum + 1, columnNum + 1];  
  34.   
  35.                 String rowStr;  
  36.                 //对数组赋值   
  37.                 for (int i = 0; i < (rowNum + 1); i++)  
  38.                 {  
  39.                     for (int colIndex = 0; colIndex < (columnNum + 1); colIndex++)  
  40.                     {  
  41.                         rowStr = null;  
  42.                         //一行中的最后一列   
  43.                         if (colIndex == columnNum && pasteText.IndexOf("\r") != -1)  
  44.                         {  
  45.                             rowStr = pasteText.Substring(0, pasteText.IndexOf("\r"));  
  46.                         }  
  47.                         //最后一行的最后一列   
  48.                         if (colIndex == columnNum && pasteText.IndexOf("\r") == -1)  
  49.                         {  
  50.                             rowStr = pasteText.Substring(0);  
  51.                         }  
  52.                         //其他行列   
  53.                         if (colIndex != columnNum)  
  54.                         {  
  55.                             rowStr = pasteText.Substring(0, pasteText.IndexOf("\t"));  
  56.                             pasteText = pasteText.Substring(pasteText.IndexOf("\t") + 1);  
  57.                         }  
  58.                         if (rowStr == string.Empty)  
  59.                             rowStr = null;  
  60.                         data[i, colIndex] = rowStr;  
  61.                     }  
  62.                     //截取下一行数据   
  63.                     pasteText = pasteText.Substring(pasteText.IndexOf("\n") + 1);  
  64.                 }  
  65.                 /*检测值是否是列头*/  
  66.                 /* 
  67.                 //获取当前选中单元格所在的列序号 
  68.                 int columnindex = dgv.CurrentRow.Cells.IndexOf(dgv.CurrentCell); 
  69.                 //获取获取当前选中单元格所在的行序号 
  70.                 int rowindex = dgv.CurrentRow.Index;*/  
  71.                 int columnindex = -1, rowindex = -1;  
  72.                 int columnindextmp = -1, rowindextmp = -1;  
  73.                 if (dgv.SelectedCells.Count != 0)  
  74.                 {  
  75.                     columnindextmp = dgv.SelectedCells[0].ColumnIndex;  
  76.                     rowindextmp = dgv.SelectedCells[0].RowIndex;  
  77.                 }  
  78.                 //取到最左上角的 单元格编号   
  79.                 foreach (DataGridViewCell cell in dgv.SelectedCells)  
  80.                 {  
  81.                     //dgv.Rows[cell.RowIndex].Selected = true;   
  82.                     columnindex = cell.ColumnIndex;  
  83.                     if (columnindex > columnindextmp)  
  84.                     {  
  85.                         //交换   
  86.                         columnindex = columnindextmp;  
  87.                     }  
  88.                     else  
  89.                         columnindextmp = columnindex;  
  90.                     rowindex = cell.RowIndex;  
  91.                     if (rowindex > rowindextmp)  
  92.                     {  
  93.                         rowindex = rowindextmp;  
  94.                         rowindextmp = rowindex;  
  95.                     }  
  96.                     else  
  97.                         rowindextmp = rowindex;  
  98.                 }  
  99.                 if (kind == -1)  
  100.                 {  
  101.                     columnindex = 0;  
  102.                     rowindex = 0;  
  103.                 }  
  104.   
  105.                 //如果行数超过当前列表行数   
  106.                 if (rowindex + rowNum + 1 > dgv.RowCount)  
  107.                 {  
  108.                     int mm = rowNum + rowindex + 1 - dgv.RowCount;  
  109.                     for (int ii = 0; ii < mm+1; ii++)  
  110.                     {  
  111.                         dgv.DataBindings.Clear();  
  112.                         DataRow row = row = ds.Tables[0].NewRow();  
  113.                         ds.Tables[0].Rows.InsertAt(row, ii + rowindex + 1);  
  114.                     }  
  115.                 }  
  116.   
  117.                 //如果列数超过当前列表列数   
  118.                 if (columnindex + columnNum + 1 > dgv.ColumnCount)  
  119.                 {  
  120.                     int mmm = columnNum + columnindex + 1 - dgv.ColumnCount;  
  121.                     for (int iii= 0; iii < mmm; iii++)  
  122.                     {  
  123.                         dgv.DataBindings.Clear();  
  124.                         DataGridViewTextBoxColumn colum = new DataGridViewTextBoxColumn();  
  125.                       dgv.Columns.Insert(columnindex+1, colum);  
  126.                     }  
  127.                 }  
  128.   
  129.                 //增加超过的行列   
  130.                 for (int j = 0; j < (rowNum + 1); j++)  
  131.                 {  
  132.                     for (int colIndex = 0; colIndex < (columnNum + 1); colIndex++)  
  133.                     {  
  134.                         if (colIndex + columnindex < dgv.Columns.Count)  
  135.                         {  
  136.                             if (dgv.Columns[colIndex + columnindex].CellType.Name == "DataGridViewTextBoxCell")  
  137.                             {  
  138.                                 if (dgv.Rows[j + rowindex].Cells[colIndex + columnindex].ReadOnly == false)  
  139.                                 {  
  140.                                     dgv.Rows[j + rowindex].Cells[colIndex + columnindex].Value = data[j, colIndex];  
  141.                                     dgv.Rows[j + rowindex].Cells[colIndex + columnindex].Selected = true;  
  142.                                 }  
  143.                             }  
  144.                         }  
  145.                     }  
  146.                 }          
  147.                 //清空剪切板内容   
  148.                 if (b_cut)  
  149.                     Clipboard.Clear();  
  150.                 return 1;  
  151.             }  
  152.             catch  
  153.             {  
  154.                 return -1;  
  155.             }  
  156.         }  
  157.         #endregion  
#region 粘贴
        public int Paste(DataGridView dgv, string pasteText, int kind, bool b_cut)
        {
            try
            {
                if (kind == 0)
                {
                    pasteText = Clipboard.GetText();
                }
                if (string.IsNullOrEmpty(pasteText))
                    return -1;
                int rowNum = 0;
                int columnNum = 0;
                //获得当前剪贴板内容的行、列数
                for (int i = 0; i < pasteText.Length; i++)
                {
                    if (pasteText.Substring(i, 1) == "\t")
                    {
                        columnNum++;
                    }
                    if (pasteText.Substring(i, 1) == "\n")
                    {
                        rowNum++;
                    }
                }
                Object[,] data;
                //粘贴板上的数据来自于EXCEL时,每行末都有\n,在DATAGRIDVIEW内复制时,最后一行末没有\n
                if (pasteText.Substring(pasteText.Length - 1, 1) == "\n")
                {
                    rowNum = rowNum - 1;
                }
                columnNum = columnNum / (rowNum + 1);
                data = new object[rowNum + 1, columnNum + 1];

                String rowStr;
                //对数组赋值
                for (int i = 0; i < (rowNum + 1); i++)
                {
                    for (int colIndex = 0; colIndex < (columnNum + 1); colIndex++)
                    {
                        rowStr = null;
                        //一行中的最后一列
                        if (colIndex == columnNum && pasteText.IndexOf("\r") != -1)
                        {
                            rowStr = pasteText.Substring(0, pasteText.IndexOf("\r"));
                        }
                        //最后一行的最后一列
                        if (colIndex == columnNum && pasteText.IndexOf("\r") == -1)
                        {
                            rowStr = pasteText.Substring(0);
                        }
                        //其他行列
                        if (colIndex != columnNum)
                        {
                            rowStr = pasteText.Substring(0, pasteText.IndexOf("\t"));
                            pasteText = pasteText.Substring(pasteText.IndexOf("\t") + 1);
                        }
                        if (rowStr == string.Empty)
                            rowStr = null;
                        data[i, colIndex] = rowStr;
                    }
                    //截取下一行数据
                    pasteText = pasteText.Substring(pasteText.IndexOf("\n") + 1);
                }
                /*检测值是否是列头*/
                /*
                //获取当前选中单元格所在的列序号
                int columnindex = dgv.CurrentRow.Cells.IndexOf(dgv.CurrentCell);
                //获取获取当前选中单元格所在的行序号
                int rowindex = dgv.CurrentRow.Index;*/
                int columnindex = -1, rowindex = -1;
                int columnindextmp = -1, rowindextmp = -1;
                if (dgv.SelectedCells.Count != 0)
                {
                    columnindextmp = dgv.SelectedCells[0].ColumnIndex;
                    rowindextmp = dgv.SelectedCells[0].RowIndex;
                }
                //取到最左上角的 单元格编号
                foreach (DataGridViewCell cell in dgv.SelectedCells)
                {
                    //dgv.Rows[cell.RowIndex].Selected = true;
                    columnindex = cell.ColumnIndex;
                    if (columnindex > columnindextmp)
                    {
                        //交换
                        columnindex = columnindextmp;
                    }
                    else
                        columnindextmp = columnindex;
                    rowindex = cell.RowIndex;
                    if (rowindex > rowindextmp)
                    {
                        rowindex = rowindextmp;
                        rowindextmp = rowindex;
                    }
                    else
                        rowindextmp = rowindex;
                }
                if (kind == -1)
                {
                    columnindex = 0;
                    rowindex = 0;
                }

                //如果行数超过当前列表行数
                if (rowindex + rowNum + 1 > dgv.RowCount)
                {
                    int mm = rowNum + rowindex + 1 - dgv.RowCount;
                    for (int ii = 0; ii < mm+1; ii++)
                    {
                        dgv.DataBindings.Clear();
                        DataRow row = row = ds.Tables[0].NewRow();
                        ds.Tables[0].Rows.InsertAt(row, ii + rowindex + 1);
                    }
                }

                //如果列数超过当前列表列数
                if (columnindex + columnNum + 1 > dgv.ColumnCount)
                {
                    int mmm = columnNum + columnindex + 1 - dgv.ColumnCount;
                    for (int iii= 0; iii < mmm; iii++)
                    {
                        dgv.DataBindings.Clear();
                        DataGridViewTextBoxColumn colum = new DataGridViewTextBoxColumn();
                      dgv.Columns.Insert(columnindex+1, colum);
                    }
                }

                //增加超过的行列
                for (int j = 0; j < (rowNum + 1); j++)
                {
                    for (int colIndex = 0; colIndex < (columnNum + 1); colIndex++)
                    {
                        if (colIndex + columnindex < dgv.Columns.Count)
                        {
                            if (dgv.Columns[colIndex + columnindex].CellType.Name == "DataGridViewTextBoxCell")
                            {
                                if (dgv.Rows[j + rowindex].Cells[colIndex + columnindex].ReadOnly == false)
                                {
                                    dgv.Rows[j + rowindex].Cells[colIndex + columnindex].Value = data[j, colIndex];
                                    dgv.Rows[j + rowindex].Cells[colIndex + columnindex].Selected = true;
                                }
                            }
                        }
                    }
                }        
                //清空剪切板内容
                if (b_cut)
                    Clipboard.Clear();
                return 1;
            }
            catch
            {
                return -1;
            }
        }
        #endregion

5.另外,因为datagridview无法编辑第一列,当插入列时,就无法在datagridview上编辑,只能增加列时就自动传一个列名,我是这样做的:

[csharp] view plain copy print ?
  1. private void 插入列ToolStripMenuItem_Click(object sender, EventArgs e)  
  2.         {     
  3.             try   
  4.             {  
  5.             DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();  
  6.             int columnindex = dataGridView1.CurrentRow.Cells.IndexOf(dataGridView1.CurrentCell);  
  7.              
  8.             string newName = "New" + (k++);  
  9.             column.HeaderText =newName;  
  10.             //column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;   
  11.             //column.CellTemplate.Style.BackColor = Color.Beige;   
  12.             dataGridView1.Columns.Insert(columnindex + 1, column);  
  13.             }  
  14.                 catch(Exception error)  
  15.             {  
  16.                 MessageBox.Show(error.Message);  
  17.               }            
  18.         }  
private void 插入列ToolStripMenuItem_Click(object sender, EventArgs e)
        {   
            try 
            {
            DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
            int columnindex = dataGridView1.CurrentRow.Cells.IndexOf(dataGridView1.CurrentCell);
           
            string newName = "New" + (k++);
            column.HeaderText =newName;
            //column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            //column.CellTemplate.Style.BackColor = Color.Beige;
            dataGridView1.Columns.Insert(columnindex + 1, column);
            }
                catch(Exception error)
            {
                MessageBox.Show(error.Message);
              }          
        }

6.其他的代码就不一一上传了,只把主要的问题和代码上传,有需要的邮件给我,我传给你。

第一次发这么长的,求人品。。。。。。。。

(附图,有图有真相,见下):


  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值