轉帖|其它|編輯:郝浩|2010-12-02 11:56:04.000|閱讀 1244 次
概述:本文繼續介紹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>
/// <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 > 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@fc6vip.cn
文章轉載自:博客轉載