彩票走势图

DatagridView 经典用法总结(二)

转帖|其它|编辑:郝浩|2010-12-02 11:56:04.000|阅读 1234 次

概述:本文继续介绍DatagridView 经典用法总结,希望对大家有帮助。

# 慧都年终大促·界面/图表报表/文档/IDE等千款热门软控件火热促销中 >>

一.DatagridView 导出数据到Excel

  有两种方法:一种是直接利用I/O读写去生成非标准格式的xls文件,速度很快。另外种就是直接使用EXCEL的COM组件实现,需要在项目中引用EXCEL的COM组件。

代码

(1)利用I/O。

1 private void button4_Click(object sender, EventArgs e)
2 {
3
4 //利用流导出Exce
5 saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
6 saveFileDialog.FileName = "mydata";
7
8 saveFileDialog.FilterIndex = 0;
9
10 saveFileDialog.RestoreDirectory = true;
11
12 saveFileDialog.CreatePrompt = true;
13
14 saveFileDialog.Title = "Export Excel File To";
15 saveFileDialog.ShowDialog();
16 Stream myStream;
17
18 try
19 {
20 myStream = saveFileDialog.OpenFile();
21 }
22 catch
23 {
24 return;
25 }
26
27 //StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
28 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
29 string str = "";
30 try
31 {
32 //写标题
33 for (int i = 0; i < this.DataGridView1.ColumnCount; i++)
34 {
35 if (i > 0)
36 {
37 str += "\t";
38 }
39 str += DataGridView1.Columns[i].HeaderText;
40
41 }
42 sw.WriteLine(str);
43 //写内容
44
45 for (int j = 0; j < DataGridView1.Rows.Count; j++)
46 {
47 string tempStr = "";
48
49 for (int k = 0; k < DataGridView1.Columns.Count; k++)
50 {
51 if (k > 0)
52 {
53 tempStr += "\t";
54 }
55
56 tempStr += DataGridView1.Rows[j].Cells[k].Value.ToString();
57
58 }
59 sw.WriteLine(tempStr);
60
61 }
62 sw.Close();
63 myStream.Close();
64
65 }
66
67 catch (Exception ex)
68 {
69 MessageBox.Show(ex.ToString());
70 }
71
72 finally
73 {
74 sw.Close();
75 myStream.Close();
76 }
77 //System.Diagnostics.Stopwatch swT = new System.Diagnostics.Stopwatch();
78 //swT.Start();
79 //long ts1 = swT.ElapsedMilliseconds;
80 //MessageBox.Show(ts1.ToString() + "\n");
81 }

(2).利用组件

首先添加Excel引用

实现代码

1 public static void DataGridViewToExcel(string fileName, DataGridView myDGV)
2 {
3 string saveFileName = "";
4 //bool fileSaved = false;
5 SaveFileDialog saveDialog = new SaveFileDialog();
6 saveDialog.DefaultExt = "xls";
7 saveDialog.Filter = "Excel文件|*.xls";
8 saveDialog.FileName = fileName;
9 saveDialog.ShowDialog();
10 saveFileName = saveDialog.FileName;
11 if (saveFileName.IndexOf(":") < 0) return; //被点了取消
12 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
13 if (xlApp == null)
14 {
15 MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
16 return;
17 }
18
19 Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
20 Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
21 Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
22
23 //写入标题
24 for (int i = 0; i < myDGV.ColumnCount; i++)
25 {
26 worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
27 }
28 //写入数值
29 for (int r = 0; r < myDGV.Rows.Count; r++)
30 {
31 for (int i = 0; i < myDGV.ColumnCount; i++)
32 {
33 worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
34 }
35 System.Windows.Forms.Application.DoEvents();
36 }
37 worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
38 //if (Microsoft.Office.Interop.cmbxType.Text != "Notification")
39 //{
40 // Excel.Range rg = worksheet.get_Range(worksheet.Cells[2, 2], worksheet.Cells[ds.Tables[0].Rows.Count + 1, 2]);
41 // rg.NumberFormat = "00000000";
42 //}
43
44 if (saveFileName != "")
45 {
46 try
47 {
48 workbook.Saved = true;
49 workbook.SaveCopyAs(saveFileName);
50 //fileSaved = true;
51 }
52 catch (Exception ex)
53 {
54 //fileSaved = false;
55 MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
56 }
57
58 }
59 //else
60 //{
61 // fileSaved = false;
62 //}
63 xlApp.Quit();
64 GC.Collect();//强行销毁
65 // if (fileSaved && System.IO.File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName); //打开EXCEL
66 MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK);
67 }

  以上两种方法都能实现Excel的导出,根据验证第一种方法的导出效率要比第二种要高很多,至于选择哪种导出方式以及性能的具体对比还需要读者详细的去衡量。

二.显示密码列

  DataGridView.CellFormatting事件

  在单元格的内容需要设置格式以便于显示时发生。

  命名空间:System.Windows.Forms

  程序集:System.Windows.Forms(在 system.windows.forms.dll 中)

  如:

  /// <summary>

  /// 单元格显示格式事件

  /// </summary>

  /// <param name="sender"></param&gt;

  /// <param name="e"></param>

  private void dataGridView1_CellFormatting(object sender,

  DataGridViewCellFormattingEventArgs e)

  {

   // 把第4列显示*号,*号的个数和实际数据的长度相同

   if (e.ColumnIndex == 3)

   {

   if (e.Value != null && e.Value.ToString().Length &gt; 0)

   {

   e.Value = new string('*',e.Value.ToString().Length);

   }

   }

   }

  DataGridView.EditingControlShowing 事件在显示用于编辑单元格的控件时发生。

命名空间: System.Windows.Forms

程序集: System.Windows.Forms(在 system.windows.forms.dll 中)

1 /// <summary>
2
3 /// 编辑单元格控件事件
4
5 /// </summary>
6
7 /// <param name="sender"></param>
8
9 /// <param name="e"></param>
10
11 private void dataGridView1_EditingControlShowing(object sender,
12
13 DataGridViewEditingControlShowingEventArgs e)
14
15 {
16
17 // 编辑第4列时,把第4列显示为*号
18
19 TextBox t = e.Control as TextBox;
20
21 if (t != null)
22
23 {
24
25 if (this.dataGridView1.CurrentCell.ColumnIndex == 3)
26
27 t.PasswordChar = '*';
28
29 else
30
31 t.PasswordChar = new char();
32
33 }
34
35 }

三、DataGridView添加任何控件

void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewTextBoxEditingControl)
{
TextBox textbox = (TextBox)e.Control;
// Panel p = (Panel)textbox.Parent; //找到当前的父控件,其实就是一个Panel,你将此Panel中的控件清空,然后你就可以在Panel中加入任何控件并随意布局了
Panel p = (Panel)e.Control.Parent;
p.Controls.Clear();

btn.Width = 38;
btn.Text = textbox.Text;
btn.Click+=new EventHandler(btn_Click);
p.Controls.Add(btn);
}

  }

  
 


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@pclwef.cn

文章转载自:博客转载

为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP