using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;
using System.IO;

namespace 在datatable上进行数据操作
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            //SetStyle(ControlStyles.OptimizedDoubleBuffer, true);//设置双缓冲
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.eventbinding();//事件绑定
            this.initdatagirdview();//把数据库载入到datagridview控件
            ).ToString()+"行";//减去列头的一行
        }

        public void eventbinding()
        {
            this.dataGridView1.ContextMenuStrip = this.contextMenuStrip1;
            this.FormClosing+=Form1_FormClosing;
            toolStripProgressBar1.Alignment = ToolStripItemAlignment.Right;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit();//保证结束所有相关的线程
        }

        public  void initdatagirdview()
        {
                    //连接数据库并把表读出
                    SqlConnection conn = new SqlConnection("server=MAGICIANLYX\\SQLEXPRESS;database=AdventureWorks;uid=magicianlyx;pwd=13113772339;");
                    string s = "select * from AdventureWorks.Person.vStateProvinceCountryRegion";
                    SqlDataAdapter sda = new SqlDataAdapter(s, conn);
                    DataSet ds = new DataSet();
                    conn.Open();
                    sda.Fill(ds);
                    conn.Close();

                    //把数据表和datagridview控件关联起来

                    DataTable dt = ds.Tables[];
                    this.dataGridView1.DataSource = dt;
                    this.datagridview_resize();//重新设置每列的宽度,使其填满窗体

            /*数据库操作
                    //删除数据表第一行
                    dt.Rows.RemoveAt(0);
                    //删除数据表第二行第一列
                    dt.Rows[1][1] = 1;
                    //在数据表第2行前插入一行空白
                    DataRow dr = dt.NewRow();
                    dt.Rows.InsertAt(dr, 1);
             * */
        }

        //重新计算即时每列的宽度
        public void datagridview_resize()
        {
            this.dataGridView1.Refresh();
            int width = (this.dataGridView1.Width - this.dataGridView1.TopLeftHeaderCell.Size.Width) / this.dataGridView1.Columns.Count;
            foreach (DataGridViewColumn dc in dataGridView1.Columns)
            {
                dc.Width = width;
            }
        }

        //重绘窗口宽度改变
        protected override void OnPaint(PaintEventArgs e)
        {
            this.datagridview_resize();
            base.OnPaint(e);
        }

        /// <summary>
        /// 保存为excel
        /// </summary>
        private void  保存为excelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.saveexcel();
        }

        public async void saveexcel()
        {
            if (File.Exists(@"C:\Users\Administrator\Documents\111.xls"))//当路径下存在文件时,删除,保证无异常
            {
                File.Delete(@"C:\Users\Administrator\Documents\111.xls");
            }

//——————————————————————————————核心代码部分

            TimeSpan t1 = new TimeSpan(DateTime.Now.Ticks);//保留实时时间,后期要计算时间差
            ;
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook excelworkbook = excel.Application.Workbooks.Add(true);
            excel.Visible = false;//是否显示excel文本

            try
            {
                //异步执行,保证前台窗口程序无卡顿
                await Task.Run(() =>
                {
                    ; i < this.dataGridView1.Columns.Count; i++)//复制表格的列头
                    {
                        excel.Cells[, i + ] = this.dataGridView1.Columns[i].HeaderText;//excel对象的行列索引是从1开始的
                        //datagridview的行列索引是从0开始的
                    }

                    ; i < ; i++)//减去列头的一行
                    {
                        ; j < this.dataGridView1.Columns.Count; j++)
                        {
                            ].Cells[j].Value==null)
                            {
                                excel.Cells[i + , j + ] ="'  ";//当表格的单元格为空时,保留行并跳过
                                break;
                            }
                            ].Cells[j].ValueType == typeof(string))
                            {
                                excel.Cells[i + , j + ] = ].Cells[j].Value.ToString();
                            }

                            else
                            {
                                excel.Cells[i + , j + ] = ].Cells[j].Value.ToString();
                            }

                        }

                       this.toolStripProgressBar1.Value++;//进度条前进

                    }
                });
            }
            catch (Exception ex)
            {
            }
            finally
            {
                //保存xls表格
                excelworkbook.SaveAs("111.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

                //释放资源
               if(excelworkbook!=null)
                   excelworkbook.Close(Missing.Value, Missing.Value, Missing.Value);
               if (excel != null)
               {
                   excel.Workbooks.Close();
                   excel.Quit();
               }

//——————————————————————后续代码非核心代码

                //计算时间差
                TimeSpan t2 = new TimeSpan(DateTime.Now.Ticks);
                TimeSpan ts = t1.Subtract(t2).Duration();
                string hours = ts.Hours.ToString(), minutes = ts.Minutes.ToString(), seconds = ts.Seconds.ToString();
                )
                {
                    hours = " + ts.Hours.ToString();
                }
                )
                {
                    minutes = " + ts.Minutes.ToString();
                }
                )
                {
                    seconds = " + ts.Seconds.ToString();
                }

               if( MessageBox.Show("花费时间\n" + hours + ":" + minutes + ":" + seconds, "完成")==DialogResult.OK)
               {
                   ;
               }
            }

        }

    }
}

不上示例文件了,毕竟数据库是我自己的

主要是两个注意的点

①Microsoft.Office.Interop.Excel.Application对象excel的行列索引是从1开始,和datagridview从0开始索引区别开来,②如果datagirdview单元的值是string类型时,后面加个 ‘     

开发时需要的Microsoft.Office.Interop.Excel.dll组件http://pan.baidu.com/s/1jGrPHrS

C# 把datagridview控件上的表格输出到excel文件的更多相关文章

  1. 使用JavaScript把页面上的表格导出为Excel文件

    如果在页面上展示了一个数据表格,而用户想把这个表格导出为Excel文件,那么在要求不高的情况下,可以不通过服务器生成表格,而是直接利用JavaScript的Blob和Object URL特性将表格导出 ...

  2. JS 将页面上的表格导出为 Excel 文件

    如果在页面上展示了一个表格,想把这个表格导出为Excel文件,那么在要求不高的情况下,可以直接利用 JavaScript 的 Blob 和 Object URL 特性将表格导出.不过,这就是利用了 E ...

  3. DataGridView控件用法一:数据绑定

    使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据. 将数据绑定到DataGridView控件非常简单和直观,在大多数情况下,只需设置DataSource属性即可.在绑 ...

  4. C#实现WinForm下DataGridView控件的拷贝和粘贴

    DataGridView控件应该是数据库应用系统最常用的控件之一,其方便性不言而喻的.往往用户在使用过程中会提出"从DataGridView空间 中拷贝数据或是向某个DataGridView ...

  5. winform datagridview控件使用

    最近做项目时,显示查询结果总需要绑定到datagridview控件上显示,总结了给datagridview绑定数据的方式,以及导出datagridview数据到excel表格,如有错误请多指教 1.直 ...

  6. 基于Winform框架DataGridView控件的SqlServer数据库查询展示功能的实现

    关键词:Winform.DataGridView.SqlServer 一个基于winform框架的C/S软件,主要实现对SqlServer数据库数据表的实时查询. 一.为DataGridView添加数 ...

  7. ADO.NET之使用DataGridView控件显示从服务器上获取的数据

    今天回顾下ADO.NET中关于使用DataGridiew控件显示数据的相关知识 理论整理: 使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据. SqlDataAd ...

  8. Winform DataGridView控件在业务逻辑上的简单使用

    需要对文字列表进行处理,然后用到DataGridView控件来处理,记录一下.效果如下: 主要是想通过禁用和取消单元格选择来使图标单元格呈现出鼠标点击的效果.因为有个单元格选择的问题困扰着我. 是这样 ...

  9. DataGridView控件

    DataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件.它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特 ...

随机推荐

  1. ASP.NET动态网站制作(2)--css(1)

    前言:这节课主要讲关于css的相关内容. 重点:1.css(Cascading Style Sheet)叠层样式表,做网页的外观,是用来控制网页样式并允许将样式信息与网页内容分离的一种标记性语言. 2 ...

  2. jquery在网页实时显示时间;

    1.定义一个显示时间的位置 <div id="shijian"> </div> 2.jquery代码 function showTime() { var c ...

  3. 【BZOJ4843】[Neerc2016]Expect to Wait 排序

    [BZOJ4843][Neerc2016]Expect to Wait Description ls最近开了一家图书馆,大家听说是ls开的,纷纷过来借书,自然就会出现供不应求的情况, 并且借书的过程类 ...

  4. iOS Dev (53) 修复UIImagePickerController偷换StatusBar颜色的问题

    版权声明:本文为 CSDN 博主 大锐哥(ID 为 prevention)原创文章,未经博主同意不得转载. https://blog.csdn.net/prevention/article/detai ...

  5. svn 出现冲突时可以使用 meld . 命令合并。 而git的冲突合并详见内容

    1.可以在任意目录使用 git mergetool --tool-help    查看 git 所支持的merge tools. 2.可以使用如下配置去设置merge tool 和 diff tool ...

  6. python splinter chromedriver下载地址(国内可用)

    http://chromedriver.storage.googleapis.com/index.html

  7. 【python】使用python写windows服务

    背景 运维windows服务器的同学都知道,windows服务器进行批量管理的时候非常麻烦,没有比较顺手的工具,虽然saltstack和ansible都能够支持windows操作,但是使用起来总感觉不 ...

  8. 将socket通信实现多进程

    我们知道,使用TCP协议需要提前建立连接,这样就只能一对一的传输,但是这样感觉十分单一,如果实现一个服务器能同时和多个客户端同信了? 这里就需要用到多线程. 处理的不同之处就在于:每一个接进来的客户都 ...

  9. web项目中从不同的路径读取文件

    项目中的配置文件可以放在classpath下,webapp下获取其他任何一个指定的绝对地址,读取这些文件就从这三个地方去找.主要代码如下: private List<String> get ...

  10. wamp server 安装后 Apache80端口占用

    提示:Your port 80 is actually used by :Server: Microsoft-HTTPAPI/2.0 解决方案:计算机->右键管理->服务和应用程序-> ...