DataGridView导出到csv格式的Excel
DataGridView导出到csv格式的Excel,此方法不需安装excel,无excel版本的麻烦。
1 #region DataGridView导出到csv格式的Excel
2 public void DataGridView2Excel_cvs(DataGridView dgv)
3 {
4 SaveFileDialog dlg = new SaveFileDialog();
5 dlg.Filter = "Excel files (*.xls)|*.xls";
6 dlg.FilterIndex = 0;
7 dlg.RestoreDirectory = true;
8 dlg.CreatePrompt = true;
9 dlg.Title = "保存为Excel文件";
10
11 if (dlg.ShowDialog() == DialogResult.OK)
12 {
13 Stream myStream;
14 myStream = dlg.OpenFile();
15 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
16 string columnTitle = "";
17 try
18 {
19 //写入列标题
20 for (int i = 0; i < dgv.ColumnCount; i++)
21 {
22 if (i > 0)
23 {
24 columnTitle += "\t";
25 }
26 columnTitle += dgv.Columns[i].HeaderText;
27 }
28 sw.WriteLine(columnTitle);
29 //写入内容
30 for (int j = 0; j < dgv.Rows.Count; j++)
31 {
32 string columnValue = "";
33 for (int k = 0; k < dgv.Columns.Count; k++)
34 {
35 if (k > 0)
36 {
37 columnValue += "\t";
38 }
39 if (dgv.Rows[j].Cells[k].Value == null)
40 {
41 columnValue += "";
42 }
43 else
44 {
45 columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
46 }
47 }
48 sw.WriteLine(columnValue);
49 }
50 }
51 catch (Exception e)
52 {
53 MessageBox.Show(e.Message);
54 }
55 finally
56 {
57 sw.Close();
58 myStream.Close();
59 }
60 }
61 }
62 #endregion
2 public void DataGridView2Excel_cvs(DataGridView dgv)
3 {
4 SaveFileDialog dlg = new SaveFileDialog();
5 dlg.Filter = "Excel files (*.xls)|*.xls";
6 dlg.FilterIndex = 0;
7 dlg.RestoreDirectory = true;
8 dlg.CreatePrompt = true;
9 dlg.Title = "保存为Excel文件";
10
11 if (dlg.ShowDialog() == DialogResult.OK)
12 {
13 Stream myStream;
14 myStream = dlg.OpenFile();
15 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
16 string columnTitle = "";
17 try
18 {
19 //写入列标题
20 for (int i = 0; i < dgv.ColumnCount; i++)
21 {
22 if (i > 0)
23 {
24 columnTitle += "\t";
25 }
26 columnTitle += dgv.Columns[i].HeaderText;
27 }
28 sw.WriteLine(columnTitle);
29 //写入内容
30 for (int j = 0; j < dgv.Rows.Count; j++)
31 {
32 string columnValue = "";
33 for (int k = 0; k < dgv.Columns.Count; k++)
34 {
35 if (k > 0)
36 {
37 columnValue += "\t";
38 }
39 if (dgv.Rows[j].Cells[k].Value == null)
40 {
41 columnValue += "";
42 }
43 else
44 {
45 columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
46 }
47 }
48 sw.WriteLine(columnValue);
49 }
50 }
51 catch (Exception e)
52 {
53 MessageBox.Show(e.Message);
54 }
55 finally
56 {
57 sw.Close();
58 myStream.Close();
59 }
60 }
61 }
62 #endregion
浙公网安备 33010602011771号