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. RRDTool详解(转)

    原创作品,允许转载,转载时请务必以超链接形式标明文章原始出处.作者信息和本声明.否则将追究法律责任.http://freeloda.blog.51cto.com/2033581/1307492 大纲 ...

  2. kfaka windows安装

    1 官网下载 解压到D:\developTools\kfaka\kafka_2.10-0.9.0.0 2 windows cmd启动 新开cmd命令:cd /d D:\developTools\kfa ...

  3. Python中的注解“@” 、Java 注解

    https://blog.csdn.net/u013474436/article/details/75675113 https://blog.csdn.net/briblue/article/deta ...

  4. 九度OJ 1163:素数 (素数)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:8496 解决:2887 题目描述: 输入一个整数n(2<=n<=10000),要求输出所有从1到这个整数之间(不包括1和这个整数 ...

  5. 九度OJ 1025:最大报销额 (01背包、DP)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:4352 解决:1055 题目描述:     现有一笔经费可以报销一定额度的发票.允许报销的发票类型包括买图书(A类).文具(B类).差旅(C ...

  6. python自动化运维六:paramiko

    paramiko是基于python实现的SSH2远程安全连接,支持认证以及密钥方式,可以实现远程命令执行,文件传输,中间SSH代理等功能.也就是采用SSH的方式进行远程访问.SSH登陆的方式可以参考之 ...

  7. LeetCode——Binary Tree Postorder Traversal

    Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...

  8. 在win7下使用git和gitlab进行code review

    1.安装 Git-2.6.3-64-bit.exe  下载地址:http://pan.baidu.com/s/1hqGvwnq 2.根据收到的邮件进入gitlab网站,并修改密码登陆 3.新建一个文件 ...

  9. SPOJ - SUBST1 New Distinct Substrings —— 后缀数组 单个字符串的子串个数

    题目链接:https://vjudge.net/problem/SPOJ-SUBST1 SUBST1 - New Distinct Substrings #suffix-array-8 Given a ...

  10. SpringBoot2.0之整合ActiveMQ(点对点模式)

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...