C#中改变字体和DataGridView中的数据导出的方法

C#中改变dgv中的字体很简单的,只需要一个简单的方法,就OK了

View Code
1 //改变字体
2   private void btnFont_Click(object sender, EventArgs e)
3 {
4 try
5 {
6 FontDialog fontDialog = new FontDialog();
7 fontDialog.Color = dgvHistroy.RowTemplate.DefaultCellStyle.ForeColor;
8 fontDialog.Font = dgvHistroy.RowTemplate.DefaultCellStyle.Font;
9 fontDialog.AllowScriptChange = true;
10 if (fontDialog.ShowDialog() != DialogResult.Cancel)
11 {
12 dgvHistroy.RowTemplate.DefaultCellStyle.Font = fontDialog.Font;//将当前选定的文字改变字体
13   }
14 DataTable ds = (DataTable)dgvHistroy.DataSource;
15 dgvHistroy.DataSource = null;
16 dgvHistroy.DataSource = ds;
17 ds.Dispose();
18 }

另外再导出dgv中的数据也是如此,暂且放在这里,以后用了会很方便的,呵呵

View Code
1 /// <summary>
2 /// 将 DataGridView的数据导出Excel
3 /// </summary>
4 /// <remarks>
5 /// using System.IO;
6 /// </remarks>
7 /// <param name="dgv"></param>
8   public static void DataGridViewToExcel(bxyztSkin.Editors.CDataGridView dgv)
9 {
10
11 SaveFileDialog dlg = new SaveFileDialog();
12 dlg.Filter = "Execl files (*.xls)|*.xls";
13 dlg.CheckFileExists = false;
14 dlg.CheckPathExists = false;
15 dlg.FilterIndex = 0;
16 dlg.RestoreDirectory = true;
17 dlg.CreatePrompt = false;
18 dlg.Title = "保存为Excel文件";
19 dlg.FileName = DateTime.Now.Ticks.ToString().Trim();
20
21 if (dlg.ShowDialog() == DialogResult.OK)
22 {
23 Stream myStream;
24 myStream = dlg.OpenFile();
25 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
26 string columnTitle = "";
27 try
28 {
29 //写入列标题
30   for (int i = 0; i < dgv.ColumnCount; i++)
31 {
32 if (i > 0)
33 {
34 columnTitle += "\t";
35 }
36 columnTitle += dgv.Columns[i].HeaderText;
37 }
38 sw.WriteLine(columnTitle);
39
40 //写入列内容
41 for (int j = 0; j < dgv.Rows.Count; j++)
42 {
43 string columnValue = "";
44 for (int k = 0; k < dgv.Columns.Count; k++)
45 {
46 if (k > 0)
47 {
48 columnValue += "\t";
49 }
50 if (dgv.Rows[j].Cells[k].Value == null)
51 columnValue += "";
52 else
53 columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
54 }
55 sw.WriteLine(columnValue);
56 }
57 sw.Close();
58 myStream.Close();
59 }
60 catch (Exception e)
61 {
62 MessageBox.Show(e.ToString());
63 }
64 finally
65 {
66 sw.Close();
67 myStream.Close();
68 }
69 }
70 }
原文地址:https://www.cnblogs.com/wsl2011/p/2057912.html