Winform的DataGridView导出到Excel

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.Office.Interop.Excel; using System.Diagnostics; namespace WinFormOne { public partial class Form7 : Form { public Form7() { InitializeComponent(); } public void ExportDataGridViewToExcel(DataGridView dataGridview1) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "导出Excel文件到"; DateTime now = DateTime.Now; saveFileDialog.FileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, '0') + now.Day.ToString().PadLeft(2, '0') + "-" + now.Hour.ToString().PadLeft(2, '0') + now.Minute.ToString().PadLeft(2, '0') + now.Second.ToString().PadLeft(2, '0'); if (saveFileDialog.ShowDialog() == DialogResult.Cancel) return; Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); string str = ""; try { //写标题 for (int i = 0; i < dataGridview1.ColumnCount; i++) { if (i > 0) { str += "/t"; } str += dataGridview1.Columns[i].HeaderText; } sw.WriteLine(str); //写内容 for (int j = 0; j < dataGridview1.Rows.Count; j++) { string tempStr = ""; for (int k = 0; k < dataGridview1.Columns.Count; k++) { if (k > 0) { tempStr += "/t"; } if (dataGridview1.Rows[j].Cells[k] != null) tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); MessageBox.Show("导出成功"); } catch (Exception e) { MessageBox.Show(e.ToString()); } finally { sw.Close(); myStream.Close(); } } private void button1_Click(object sender, EventArgs e) { ExportDataGridViewToExcel(dataGridView1); } private void Form7_Load(object sender, EventArgs e) { System.Data.DataTable dt = new System.Data.DataTable(); dt.Columns.Add("A", typeof(string)); dt.Columns.Add("B", typeof(string)); dt.Columns.Add("C",typeof(string)); dt.Columns.Add("D", typeof(string)); dt.Columns.Add("E", typeof(string)); DataRow dr = dt.NewRow(); dr["A"] = "AAAAA"; dr["B"] = "BBBBB"; dr["C"] = "CCCCC"; dr["D"] = "DDDD"; dr["E"] = "EEEE"; DataRow dr1 = dt.NewRow(); dr1["A"] = "WWW"; dr1["B"] = "RRR"; dr1["C"] = "TTT"; dr1["D"] = "QQQ"; dr1["E"] = "EEE"; dt.Rows.Add(dr); dt.Rows.Add(dr1); dataGridView1.DataSource = dt; } } }

你可能感兴趣的:(Winform的DataGridView导出到Excel)