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

来源:互联网 发布:燕麦片的做法 知乎 编辑:程序博客网 时间:2024/05/21 17:07
1.导入Excel。代码走先。

[csharp] view plaincopyprint?
  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.       }  
[csharp] view plaincopyprint?
  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.         }  

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


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

[csharp] view plaincopyprint?
  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.        }  
[csharp] view plaincopyprint?
  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.         }  


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

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

[csharp] view plaincopyprint?
  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  

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

[csharp] view plaincopyprint?
  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.         }  

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

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

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


原创粉丝点击