先从数据库中获取数据,绑定在datagridview中,再从dategridview中导出为excel文件

1、新建窗体,把控件datagridview和按钮设置好,如图

2、设置datagridview绑定数据表的字段

1)点击datagriview右上角,弹出编辑列,添加列

2)点击添加列,新建数据,跟数据库中数据表的列名一样

3、获取数据库中数据表的方法

SqlConnection conn = null;
        /// <summary>
        /// 查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            conn = DBHelp.GetConnection();  //获取数据库连接,并开启连接
            string sql = "select * from UseTab";   //查询数据表的 sql语句
            DataSet ds = new DataSet();
            SqlDataAdapter sda = new SqlDataAdapter(sql,conn);
            sda.Fill(ds);
            DataTable dt = ds.Tables[0];   //获取数据表的数据
            this.dgvUseName.DataSource = dt;  //把dattable绑定datagridview
            DBHelp.CloseConnection(conn);   //关闭连接
            //选择整行显示数据
            this.dgvUseName.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
           //选择是否只读
            this.dgvUseName.ReadOnly = true;
        }

4、导出为excel文件的方法

private void btnExport_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel 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 = saveFileDialog.OpenFile();
            StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
            string str = "";
            try
            {
                //写标题     
                for (int i = 0; i < this.dgvUseName.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += this.dgvUseName.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                 //写内容   
                for (int j = 0; j < this.dgvUseName.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < this.dgvUseName.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        tempStr += this.dgvUseName.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();
            }
        }

5、数据库辅助类

class DBHelp
    {
        //连接字符串
        static String str = "server=.;database=TestDB;uid=sa;pwd=sa";
        static SqlConnection conn = null;
        static SqlCommand cmd = null;
        static int result=0;
       
        /// <summary>
        /// 获取可用连接
        /// </summary>
        /// <returns>数据库连接对象</returns>
        public static SqlConnection GetConnection() {
            conn = new SqlConnection(str);
            conn.Open();
            return conn;
        }
        /// <summary>
        /// 关闭连接对象
        /// </summary>
        /// <param name="conn">连接对象</param>
        public static void CloseConnection(SqlConnection conn) {
            if (conn != null && conn.State == System.Data.ConnectionState.Open) {
                conn.Close();
            }    
        }

}

6、最后导出的效果图

保存时,弹出的窗体

打开excel文件查看数据

参考的导出方法来自这个地址:http://www.cnblogs.com/hfzsjz/archive/2013/05/07/3064231.html

C#中dategridview数据导出为excel文件的更多相关文章

  1. Qt中将QTableView中的数据导出为Excel文件

    如果你在做一个报表类的程序,可能将内容导出为Excel文件是一项必须的功能.之前使用MFC的时候我就写过一个类,用于将grid中的数据导出为Excel文件.在使用了QtSql模块后,我很容易的将这个类 ...

  2. C#将数据集DataSet中的数据导出到EXCEL文件的几种方法

    using System; using System.Collections.Generic; using System.Text; using System.Data; using System.W ...

  3. html5中 table数据导出到excel文件

    JS代码: /** * table数据导出到excel * 形参 table : tableId ; * sheetName : 工作薄名 * fileName : 文件名 * linkId :隐藏的 ...

  4. vb.net-三种将datagridview数据导出为excel文件的函数

    第一种方法较慢,但是数据格式都比较好,需要引用excel的 Microsoft.Office.Interop.Excel.dll  office.dll #Region "导出excel函数 ...

  5. 机房收费系统——在VB中将MSHFlexGrid控件中的数据导出到Excel

    机房收费系统中,好多查询的窗体都包含同一个功能:将数据库中查询到的数据显示在MSHFlexGrid控件中,然后再把MSHFlexGrid控件中的数据导出到Excel表格中. 虽然之前做过学生信息管理系 ...

  6. VB将MSHFlexGrid数据导出到Excel文件通用功能

    1.通用导出Excel功能. 2.将 MSHFlexGrid数据导出到Excel文件通用功能. 3.具体代码如下: '将下列代码保存到一模块文件中,调用方法:Export fgrid1,cd1 Pub ...

  7. 用node.js写一个简单爬虫,并将数据导出为 excel 文件

    引子 最近折腾node,最开始像无头苍蝇一样到处找资料,然而多数没什么卵用,都在瞎比比.在一阵瞎搞后,我来分享一下初步学习node的三个过程: 1 撸一遍NODE入门,对其有个基本的了解: 2 撸一遍 ...

  8. Asp.net网页中DataGridView数据导出到Excel

    经过上网找资料,终于找到一种可以直接将GridView中数据导出到Excel文件的方法,归纳方法如下: 1. 注:其中的字符集格式若改为“GB2312”,导出的部分数据可能为乱码: 导出之前需要关闭分 ...

  9. WPF-将DataGrid控件中的数据导出到Excel

    原文:WPF-将DataGrid控件中的数据导出到Excel 导出至Excel是非常常见,我们可以用很多类库,例如Aspose.NOPI.Interop,在这里我们使用微软自家的工具.我的WPF绑定的 ...

随机推荐

  1. ECShop商品详细页 实现尺码颜色关联显示库存数量

    效果如下: 要开模板文件 goods.dwt  把选择尺码跟颜色的代码替换成如下,(不同模板代码可能不一样,对照去替换) <!-- {foreach from=$spec.values item ...

  2. Android学习笔记----TimerTask中显示Toast的问题

    今天想在TimerTask的run函数中调用Toast显示一下提示信息,却总是导致程序崩溃.可是try语句块却又无法捕获到异常,代码如下: ...... Timer timer = new Timer ...

  3. Windows调试学习笔记:(二)WinDBG调试.NET程序示例

    好不容易把环境打好了,一定要试试牛刀.我创建了一个极其简单的程序(如下).让我们期待会有好的结果吧,阿门! using System; using System.Collections.Generic ...

  4. 从Tmux 转到GNU Screen

    网上很多地方都说Tmux比GNU Screen要好用,不过无意间看到这篇Switching from tmux to GNU Screen之后,我发现GNU Screen的窗口/区域概念更好,至少是更 ...

  5. Visual Studio 新建项目报错" this template attempted to load component assembly 'NuGet.VisualStudio.Interop, ….".

    "Error: this template attempted to load component assembly 'NuGet.VisualStudio.Interop, Version ...

  6. SVN: bdb: BDB1538 Program version 5.3 doesn't match environment version 4.7

    Q:bdb: BDB1538 Program version 5.3 doesn't match environment version 4.7 A: svnadmin recover /var/wh ...

  7. Android JNI 之 JNIEnv 解析

    jni.h文件 : 了解 JNI 需要配合 jni.h 文件, jni.h 是 Google NDK 中的一个文件, 位置是 $/android-ndk-r9d/platforms/android-1 ...

  8. LeetCode:4_Median of Two Sorted Arrays | 求两个排序数组的中位数 | Hard

    题目: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the ...

  9. Java数组,去掉重复值、增加、删除数组元素

    import java.util.List; import java.util.ArrayList; import java.util.Set; import java.util.HashSet; p ...

  10. Part 2: Oracle E-Business Suite on Cloud FAQ

    Running Oracle E-Business Suite on Oracle Cloud is simple, but it doesn't take too much effort to co ...