WinForm c# GridView导出Excel
2013-05-07 10:13
507 查看
WinForm GridView导出Excel using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; namespace gridview导出excel { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con = new SqlConnection("server=.;database=TestDB;uid=sa;pwd="); private void btnSelect_Click(object sender, EventArgs e) { string Sql = "SELECT UserName,UserAge,UserPhone,UserAddress From tb_userinfo"; con.Open(); SqlDataAdapter da; da = new SqlDataAdapter(Sql, con); DataSet ds = new DataSet(); da.Fill(ds, "tb_userinfo"); this.dataGridView1.DataSource = ds.Tables["tb_userinfo"].DefaultView; con.Close(); } private void btnOut_Click(object sender, EventArgs e) { 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'); saveFileDialog.ShowDialog(); 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"; } tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString(); } sw.WriteLine(tempStr); } sw.Close(); myStream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { sw.Close(); myStream.Close(); } } } }
相关文章推荐
- C#导出GridView的数据到Excel以及Excel导入SQL Server
- C#编写GridView导出EXCEL
- winForm中C#实现Excel的导出
- C# Winform中导出数据到Excel
- C#导出GridView数据到Excel文件类实例
- C# 将数据导出到Excel汇总Webform,Winform(转)
- c# Winform程序实现多sheet的Excel文件导入与导出
- c# winform DataGridView导出数据到Excel中,可以导出当前页和全部数据
- c#.net 使用NPOI导入导出标准Excel (asp.net winform csharp)
- C# WinForm程序中将DataGridView中的数据导出为EXCEL
- [C#]WinForm中DataGrid扩展 - 快速导出Excel文件
- C#使用winform简单导出Excel的方法
- [Excel] C#GridViewExport帮助类,美化导出 (转载)
- C# 将GridView导出为Excel注意事项
- C# 在office2007 gridview导出到excel
- Datatable或Gridview中的数据导出为excel表格数据(Asp.net C#)
- C# WinForm DataTable 导出 Excel 多行表头、合并单元格
- C#winForm导出excel
- C#winform从数据集导出Excel(带指定Excel样式)
- C#GridView控件导出Excel及多层表头类