datagridview导出excel
2010-09-25 23:38
162 查看
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; namespace DXGXGIS { class ExportToExcel { public void ExportDataGridViewToExcel(DataGridView dataGridview1) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl 文件(*.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(); if (saveFileDialog.ShowDialog() == DialogResult.OK) { Stream myStream; myStream = saveFileDialog.OpenFile(); StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312")); string str = ""; string tempStr = string.Empty; 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 - 1; j++) { 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); tempStr = string.Empty; } sw.Close(); myStream.Close(); MessageBox.Show("导出成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception e) { MessageBox.Show(e.ToString(), "出现异常", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { sw.Close(); myStream.Close(); } } else { MessageBox.Show("导出失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } }
相关文章推荐
- C# winform DataGridView导出到EXCEL
- 如何将datagridview中的数据导出到Excel中?
- WinForm下DataGridView导出Excel的实现
- c# datagridview导出到excel
- C#datagridview根据某一属性不同导出多份excel
- C# WinForm下DataGridView导出Excel的实现
- DataGridView导出到Excel的三个方法
- DataGridView导出数据到Excel的三种方式
- datagridview控件--导出Excel
- C#之四十三 从DataGridView导出数据到Excel
- 从datagridview中导出数据到excel
- C# DataGridView 导出 Excel(根据Excel版本显示选择不同后缀格式xls或xlsx)
- C# datagridview 导出EXCEL 类
- DataGridView导出到Excel的三个方法 (转载)
- datagridview 导出excel的两种方式
- VB.net 将dataGridView中的数据导出到excel
- c# datagridview导出导入excel 如果用流的方式打开,可以导出,无法读取
- WinForm下DataGridView导出Excel的实现 转处:http://seloba.iteye.com/blog/1017715
- 行添加DataGridView导出Excel的数据表格
- C#将dataGridView中显示的数据导出到Excel(大数据量超有用版)