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【转载】的更多相关文章

  1. DataGridView导出到Excel的三个方法

    #region DataGridView数据显示到Excel /// <summary> /// 打开Excel并将DataGridView控件中数据导出到Excel /// </s ...

  2. C# - VS2019 DataGridView导出到Excel的三种方法

    //原文出处:http://www.yongfa365.com/Item/DataGridViewToExcel.html 1 #region DataGridView数据显示到Excel /// & ...

  3. Winform 中 dataGridView 导出到Excel中的方法总结

    最近,在做CS端数据导出到Excel中时网上找了很多代码感觉都不是自己想要的,通过自己的整理归纳得到一个比较通用的方法,就给大家分享一下: 该方法需要用到两个参数(即对象),一个  DataGridV ...

  4. winform DataGridView 导出到Excel表格 分类: WinForm 2014-07-04 10:48 177人阅读 评论(0) 收藏

    public bool ExportDataGridview(DataGridView gridView)         {             if (gridView.Rows.Count ...

  5. DataGridView 导出到Excel

    #region 导出四个表格到Excel /// <summary> /// 导出四个表格到Excel /// </summary> /// <param name=&q ...

  6. [WinForm]dataGridView导出到EXCEL

    方法一: SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; ...

  7. WinForm中DataGridView导出为Excel(快速版)

    public static void ExportExcel(DataGridView myDGV, string fileName) { string saveFileName = fileName ...

  8. datagridview导出到excel

    Microsoft.Office.Interop.Excel.Range range = null; string saveFileName = ""; bool fileSave ...

  9. 学习笔记 DataGridView数据导出为Excel

    DataGridView数据导出为Excel   怎样把WinForm下的“DGV”里的绑定数据库后的数据导出到Excel中. 比如:在窗体里有个一“DGV”,DataGridView1,绑定了数据源 ...

随机推荐

  1. editplus如何设置不自动备份

    依次选择:工具,参数设置,文件(默认展开的,要缩回),然后看右边“保存文件时创建备份”,前面的框不要打勾,应用,确定

  2. java24 手写服务器最终版本

    手写服务器最终版本; <?xml version="1.0" encoding="UTF-8"?> <web-app> <serv ...

  3. ant有什么用

    内容摘要: ANT是一个基于Java的自动化脚本引擎,脚本格式为XML.除了做Java编译相关任务外,ANT还可以通过插件实现很多应用的调用. 1)ANT的基本概念: 2)ANT的安装:解包,设置路径 ...

  4. opai_suki

  5. 使用Keytool工具生成证书Keystore和证书签名请求文件

    内容概览: keytool的几个常用的命令. 1.创建证书 2.查看证书库 3.导出证书文件 4.导入证书的信息 5.查看证书信息 6.删除密钥库中的条目 7.修改证书条目的口令 ---------- ...

  6. EF6调用存储过程,返回多个结果集处理

    链接:http://www.codeproject.com/Articles/675933/Returning-Multiple-Result-Sets-from-an-Entity-Fram 案例: ...

  7. Jquery Table添加行、删除行

    html页面代码 <table id="tblUserInfo"> </table> Js代码 function DealUserInfo(qty){ ) ...

  8. 20160331javaweb 之JSP page 指令

  9. 2014年的Google I/O app设计中的材料设计-渣渣的翻译

    又是一篇翻译,用了三个多小时.http://android-developers.blogspot.co.id/2014/08/material-design-in-2014-google-io-ap ...

  10. 【制作镜像Win*】环境准备

    1. 保证网络通 2. 保证系统为centos6.x/rhel 6.x 3. yum源正确,推荐使用utsc源,nailgun也ok 4.安装软件包 virsh list guestmount yum ...