c# datagridview导出到excel【转载】
c# datagridview导出到excel【转载】 http://hi.baidu.com/weizier/blog/item/8212caea1123b4d6d439c9fe.html
本作者使用的是方法二:
方法一:添加dll引用
右击选择你所在的项目的“引用”,选择“添加引用”。
弹出“添加引用”对话框。
选择“COM”选项卡。
选择“Microsoft Excel 11.0 Object Library”
单击“确定”按钮。
代码
public static bool ExportForDataGridview(DataGridView gridView, string fileName, bool isShowExcle)
{ //建立Excel对象 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
if (app == null)
{
return false;
} app.Visible = isShowExcle;
Workbooks workbooks = app.Workbooks;
_Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Sheets sheets = workbook.Worksheets;
_Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
return false;
}
string sLen = "";
//取得最后一列列名
char H = (char)(64 + gridView.ColumnCount / 26);
char L = (char)(64 + gridView.ColumnCount % 26);
if (gridView.ColumnCount < 26)
{
sLen = L.ToString();
}
else
{
sLen = H.ToString() + L.ToString();
} //标题
string sTmp = sLen + "1";
Range ranCaption = worksheet.get_Range(sTmp, "A1");
string[] asCaption = new string[gridView.ColumnCount];
for (int i = 0; i < gridView.ColumnCount; i++)
{
asCaption[i] = gridView.Columns[i].HeaderText;
}
ranCaption.Value2 = asCaption; //数据
object[] obj = new object[gridView.Columns.Count];
for (int r = 0; r < gridView.RowCount - 1; r++)
{
for (int l = 0; l < gridView.Columns.Count; l++)
{
if (gridView[l, r].ValueType == typeof(DateTime))
{
obj[l] = gridView[l, r].Value.ToString();
}
else
{
obj[l] = gridView[l, r].Value;
}
}
string cell1 = sLen + ((int)(r + 2)).ToString();
string cell2 = "A" + ((int)(r + 2)).ToString();
Range ran = worksheet.get_Range(cell1, cell2);
ran.Value2 = obj;
}
//保存
workbook.SaveCopyAs(fileName);
workbook.Saved = true;
}
finally
{
//关闭
app.UserControl = false;
app.Quit();
}
return true; }
方法二
用流保存成xls文件. 这种方法比较好,不用引用Excel组件. 下面是具体例子,可以参考
using System.IO;
///<summary>
///另存新档按钮
///</summary>
private void SaveAs() //另存新档按钮 导出成Excel
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
//StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
//写标题
for (int i = 0; i < dgvAgeWeekSex.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dgvAgeWeekSex.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < dgvAgeWeekSex.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dgvAgeWeekSex.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dgvAgeWeekSex.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
方法三
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Microsoft.Office.Interop.Excel;
namespace AssetsUI {
public partial class FrmPrint : Form {
DataSet publicDs = null;
//Form main=null;
public FrmPrint(System.Data.DataSet privateDs) {//System.Data.DataSet privateDs
publicDs = privateDs;
//main=f;
InitializeComponent();
}
string filePath="";
System.Data.DataTable dt=new System.Data.DataTable();
DataSet ds=new DataSet();
private void btnOpen_Click(object sender, EventArgs e) {
if(DialogResult.OK==this.saveFileDialog1.ShowDialog()){//打开“打开文件对话框”
filePath=this.saveFileDialog1.FileName;
this.txtFileName.Text=filePath;
}
}
public void print(){
int rowIndex = 1;//行起始坐标
int colIndex = 0;//列起始坐标
ApplicationClass EXL = new ApplicationClass();
_Workbook WBook;
_Worksheet WSheet;
if (EXL == null) {
throw (new Exception("EXCEL没有安装!"));
}
WBook = EXL.Workbooks.Add(true);
WSheet = (_Worksheet)WBook.ActiveSheet;
WSheet.Name = this.txtCaption.Text;//"我的Excel";//表名字
//---------------------
foreach (DataColumn col in publicDs.Tables[0].Columns)
{
colIndex++;
WSheet.Cells[1, colIndex] = col.ToString();
WSheet.get_Range(WSheet.Cells[4, colIndex], WSheet.Cells[4, colIndex]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
//colIndex++;
//WSheet.Cells[4, colIndex] = "列2";
//WSheet.get_Range(WSheet.Cells[4, colIndex], WSheet.Cells[4, colIndex]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
}
foreach(DataRow row in publicDs.Tables[0].Rows)
{
colIndex = 0;
rowIndex++;
foreach (DataColumn c in publicDs.Tables[0].Columns){
colIndex++;
WSheet.Cells[rowIndex, colIndex] = row[colIndex-1].ToString();
WSheet.get_Range(WSheet.Cells[rowIndex, colIndex],WSheet.Cells[rowIndex, colIndex]).HorizontalAlignment =Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
}
}
//定义一个使用缺省参数的对象
object oMissiong = System.Reflection.Missing.Value;
WSheet.SaveAs(filePath, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
WBook.Save();
//停止excel应用程序
EXL.Quit();
//释放资源
System.Runtime.InteropServices.Marshal.ReleaseComObject(WSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(WBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(EXL);
System.GC.Collect();//强制垃圾回收
//--------end--------------
}
private void FrmPrint_Load(object sender, EventArgs e) {
this.txtCaption.Text=DateTime.Now.ToShortDateString();
dt=publicDs.Tables[0].Clone();
//foreach(DataColumn c in dt.Columns){
//for(int i=0;i<dt.Columns.Count;i++){
// dt.Columns.Add("a");
//}
dataGridView1.DataSource = dt;
}
private void btnOK_Click(object sender, EventArgs e) {
print();
}
}
}
c# datagridview导出到excel【转载】的更多相关文章
- DataGridView导出到Excel的三个方法
#region DataGridView数据显示到Excel /// <summary> /// 打开Excel并将DataGridView控件中数据导出到Excel /// </s ...
- C# - VS2019 DataGridView导出到Excel的三种方法
//原文出处:http://www.yongfa365.com/Item/DataGridViewToExcel.html 1 #region DataGridView数据显示到Excel /// & ...
- Winform 中 dataGridView 导出到Excel中的方法总结
最近,在做CS端数据导出到Excel中时网上找了很多代码感觉都不是自己想要的,通过自己的整理归纳得到一个比较通用的方法,就给大家分享一下: 该方法需要用到两个参数(即对象),一个 DataGridV ...
- winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏
public bool ExportDataGridview(DataGridView gridView) { if (gridView.Rows.Count ...
- DataGridView 导出到Excel
#region 导出四个表格到Excel /// <summary> /// 导出四个表格到Excel /// </summary> /// <param name=&q ...
- [WinForm]dataGridView导出到EXCEL
方法一: SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; ...
- WinForm中DataGridView导出为Excel(快速版)
public static void ExportExcel(DataGridView myDGV, string fileName) { string saveFileName = fileName ...
- datagridview导出到excel
Microsoft.Office.Interop.Excel.Range range = null; string saveFileName = ""; bool fileSave ...
- 学习笔记 DataGridView数据导出为Excel
DataGridView数据导出为Excel 怎样把WinForm下的“DGV”里的绑定数据库后的数据导出到Excel中. 比如:在窗体里有个一“DGV”,DataGridView1,绑定了数据源 ...
随机推荐
- 微信中QQ表情的解析(php)
微信公众平台接受的消息中,标签是用'/:'开头的字符串表示的,假设要在网页上显示(比方制作微信大屏幕),就须要进行转换. 所以我向微信公众平台按顺序发送了各个QQ表情,在微信公众平台后台能够看到接受的 ...
- android中利用实现二级联动的效果
按照惯例,首先上一张效果图. 本篇文章实现的效果就是如图中所圈的那样,实现类似于HTML中的二级联动的效果. 对于第一个选项我们读取的是本地xml文件来填充数据的, 对于第二个选项我们读取的是通过中央 ...
- mybatis完美的实战教程
文件夹(? )[-] (读者注:事实上这个应该叫做非常基础的入门一下下,假设你看过Hibernate了那这个就非常的简单) 文章来源:http://blog.csdn.net/techbirds_ba ...
- stoi的例子
9.51 设计一类,它又三个unsigned成员,分别表示年月日.为其编写构造函数,接受一个表示日期的string参数. 程序如下: #include<iostream> #include ...
- 局域网动态ip
1. 局域网IP对网速没有任何影响.点“开始”“设置”进入“网络连接” 右击“本地连接”选择“属性”选中“Internet协议(TCP/IP)” 在下面的一些按钮中点“属性”,之后你可以设置局域网IP ...
- Thumb
这个控件,真不好介绍,MSDN上也是草草几句,反正就是可以让用户拖动的玩意儿,但是,你会发现,当你在该控件上拖动时,它没有反响,也就是说这个东西默认不做任何操作的,它是赖在那里什么都不干,除非你去踢上 ...
- Thinkphp单字母函数使用指南
Thinkphp单字母函数使用指南A方法A方法用于在内部实例化控制器,调用格式:A('[项目://][分组/]模块','控制器层名称')最简单的用法: $User = A('User'); 复制代码 ...
- MVC知识总结(前序)
距离2015年的来临还有1天的时间,是时候总结一下今年的经过脑子的知识了,由于今年里工作中接触MVC的时间特别多,所以打算针对MVC这个东西的知识进行一个总结,好歹对得起在几个项目中用了MVC来进行开 ...
- java将Excel文件(xlsx,xls)转换为csv文件
http://blog.csdn.net/bryan__/article/details/40715309
- 学习笔记_过滤器详细_2(过滤器JavaWeb三大组件之一)
过滤器详细 5 四种拦截方式 我们来做个测试,写一个过滤器,指定过滤的资源为b.jsp,然后我们在浏览器中直接访问b.jsp,你会发现过滤器执行了! 但是,当我们在a.jsp中request.getR ...