C# 把datagridview控件上的表格输出到excel文件
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文件的更多相关文章
- 使用JavaScript把页面上的表格导出为Excel文件
如果在页面上展示了一个数据表格,而用户想把这个表格导出为Excel文件,那么在要求不高的情况下,可以不通过服务器生成表格,而是直接利用JavaScript的Blob和Object URL特性将表格导出 ...
- JS 将页面上的表格导出为 Excel 文件
如果在页面上展示了一个表格,想把这个表格导出为Excel文件,那么在要求不高的情况下,可以直接利用 JavaScript 的 Blob 和 Object URL 特性将表格导出.不过,这就是利用了 E ...
- DataGridView控件用法一:数据绑定
使用DataGridView控件,可以显示和编辑来自多种不同类型的数据源的表格数据. 将数据绑定到DataGridView控件非常简单和直观,在大多数情况下,只需设置DataSource属性即可.在绑 ...
- C#实现WinForm下DataGridView控件的拷贝和粘贴
DataGridView控件应该是数据库应用系统最常用的控件之一,其方便性不言而喻的.往往用户在使用过程中会提出"从DataGridView空间 中拷贝数据或是向某个DataGridView ...
- winform datagridview控件使用
最近做项目时,显示查询结果总需要绑定到datagridview控件上显示,总结了给datagridview绑定数据的方式,以及导出datagridview数据到excel表格,如有错误请多指教 1.直 ...
- 基于Winform框架DataGridView控件的SqlServer数据库查询展示功能的实现
关键词:Winform.DataGridView.SqlServer 一个基于winform框架的C/S软件,主要实现对SqlServer数据库数据表的实时查询. 一.为DataGridView添加数 ...
- ADO.NET之使用DataGridView控件显示从服务器上获取的数据
今天回顾下ADO.NET中关于使用DataGridiew控件显示数据的相关知识 理论整理: 使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据. SqlDataAd ...
- Winform DataGridView控件在业务逻辑上的简单使用
需要对文字列表进行处理,然后用到DataGridView控件来处理,记录一下.效果如下: 主要是想通过禁用和取消单元格选择来使图标单元格呈现出鼠标点击的效果.因为有个单元格选择的问题困扰着我. 是这样 ...
- DataGridView控件
DataGridView控件 DataGridView是用于Windows Froms 2.0的新网格控件.它可以取代先前版本中DataGrid控件,它易于使用并高度可定制,支持很多我们的用户需要的特 ...
随机推荐
- [项目构建 十一]babasport 购物车的原理及实现.
今天来开始写一下关于购物车的东西, 这里首先抛出四个问题: 1)用户没登陆用户名和密码,添加商品, 关闭浏览器再打开后 不登录用户名和密码 问:购物车商品还在吗? 2)用户登陆了用户名密码,添加商品, ...
- gulp的使用方法
---恢复内容开始--- 什么是gulp? Gulp.js是一个自动化构建工具,开发者可以使用它在项目开发过程中自动执行常见任务. 使用步骤: 1.全局安装gulp: npm install - ...
- Eclipse打jar包的方法
1.准备主清单文件 “MANIFEST.MF” Manifest-Version: 1.0 Class-Path: lib/commons-codec.jar lib/commons-httpclie ...
- java中Random(long seed)方法与rRandom()方法的使用产生随机数
Random 类作为JAVA中用于产生的随机数 ,new Random(10) :10是种子数. 注意:Random 的一个特点是:相同种子数的Random对象,对应相同次数生成的随机数字是完全相 ...
- python 创建一个实例:步骤二 添加行为方法,编写方法
添加方法 class Person(): def __init__(self,name,job=None,pay=0): self.name= name self.job = job self.pay ...
- LeetCode 017 4Sum
[题目] Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d ...
- ubuntu安装opencv(自己编译)
如果只需要python的,只需pip install opencv-python,然后apt-get一下下面第一点的东东. 1/ sudo apt-get install build-essentia ...
- python3使用pdfminer3k解析pdf文件
安装pdfminer模块 pip3 install pdfminer3k 代码如下 #!/usr/bin/env python # coding:utf8 # author:Z time:2018/7 ...
- SDUT 2133 数据结构实验之栈三:后缀式求值
数据结构实验之栈三:后缀式求值 Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^ 题目描述 对于一个基于二元运算符的后缀表示式(基本操作数都是 ...
- CEF与MLS快速交换对比
MLS快速交换 到达某特定目的地址的IP包通常会引起数据包流,即假设交换过到特定目标的包之后,另一个很可能不久也会到达.通过构建最近交换目标的高速缓存,可以减少包在全路由表中查找同一目标的次数,这种“ ...