最近工作中需要做一个把用户信息作为excel导出的功能,就顺便整理搜集了一些常用的导出文件的源代码,以供以后不时之需,也希望能给大家带来一些方便

一、DataSet数据集内数据转化为Excel

// 作用:把DataSet数据集内数据转化为Excel文件
// 描述:这些关于Excel的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后
// 生成Xml格式,再导入数据库! 
// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。

public void DataSetToExcel(DataSet ds,string FileName)
{
try
{
//Web页面定义
//System.Web.UI.Page mypage=new System.Web.UI.Page(); HttpResponse resp;
resp=HttpContext.Current.Response;
resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
resp.ContentType="application/ms-excel"; //变量定义
string colHeaders=null;
string Is_item=null; //显示格式定义//////////////// //文件流操作定义
//FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
//StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312")); StringWriter sfw=new StringWriter();
//定义表对象与行对象,同时用DataSet对其值进行初始化
System.Data.DataTable dt=ds.Tables[];
DataRow[] myRow=dt.Select();
int i=;
int cl=dt.Columns.Count; //取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for(i=;i<cl;i++)
{
//if(i==(cl-1)) //最后一列,加\n
// colHeaders+=dt.Columns[i].Caption.ToString();
//else
colHeaders+=dt.Columns[i].Caption.ToString()+"\t";
}
sfw.WriteLine(colHeaders);
//sw.WriteLine(colHeaders); //逐行处理数据
foreach(DataRow row in myRow)
{
//当前数据写入
for(i=;i<cl;i++)
{
//if(i==(cl-1))
// Is_item+=row[i].ToString()+"\n";
//else
Is_item+=row[i].ToString()+"\t";
}
sfw.WriteLine(Is_item);
//sw.WriteLine(Is_item);
Is_item=null;
}
resp.Write(sfw);
//resp.Clear();
resp.End();
}
catch(Exception e)
{
throw e;
}
}

二、DataSet数据集内数据转化为Excel文件(2)

/// <summary>
/// 作用:把DataSet数据集内数据转化为Excel文件
/// 描述:导出Excel文件
/// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。

/// </summary>

public class ExportFiles
{
private string filePath = "";
public ExportFiles(string excel_path)
{
//
// TODO: 在此处添加构造函数逻辑
//
filePath = excel_path;
}
/// <summary>
/// 将指定的Dataset导出到Excel文件
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public bool ExportToExcel(System.Data.DataSet ds, string ReportName)
{
if (ds.Tables[].Rows.Count == )
{
MessageBox.Show("数据集为空");
}
Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
Workbook xlbook = xlapp.Workbooks.Add(true);
Worksheet xlsheet = (Worksheet)xlbook.Worksheets[];
Range range = xlsheet.get_Range(xlapp.Cells[, ], xlapp.Cells[, ds.Tables[].Columns.Count]);
range.MergeCells = true;
xlapp.ActiveCell.FormulaR1C1 = ReportName;
xlapp.ActiveCell.Font.Size = ;
xlapp.ActiveCell.Font.Bold = true;
xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
int colIndex = ;
int RowIndex = ;
//开始写入每列的标题
foreach (DataColumn dc in ds.Tables[].Columns)
{
colIndex++;
xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
}
//开始写入内容
int RowCount = ds.Tables[].Rows.Count;//行数
for (int i = ; i < RowCount; i++)
{
RowIndex++;
int ColCount = ds.Tables[].Columns.Count;//列数
for (colIndex = ; colIndex <= ColCount; colIndex++)
{
xlsheet.Cells[RowIndex, colIndex] = ds.Tables[].Rows[i][colIndex - ];//dg[i, colIndex - 1];
xlsheet.Cells.ColumnWidth = ds.Tables[].Rows[i][colIndex - ].ToString().Length;
}
} xlbook.Saved = true;
xlbook.SaveCopyAs(filePath);
xlapp.Quit();
GC.Collect();
return true;
} public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName)
{
if (ds.Tables[].Rows.Count == )
{
MessageBox.Show("数据集为空");
}
string FileName = filePath; //System.Data.DataTable dt = new System.Data.DataTable();
FileStream objFileStream;
StreamWriter objStreamWriter;
string strLine = "";
objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode); strLine = ReportName;
objStreamWriter.WriteLine(strLine);
strLine = ""; for (int i = ; i < ds.Tables[].Columns.Count; i++)
{
strLine = strLine + ds.Tables[].Columns[i].ColumnName.ToString() + " " + Convert.ToChar();
}
objStreamWriter.WriteLine(strLine);
strLine = ""; for (int i = ; i < ds.Tables[].Rows.Count; i++)
{
strLine = strLine + (i + ) + Convert.ToChar();
for (int j = ; j < ds.Tables[].Columns.Count; j++)
{
strLine = strLine + ds.Tables[].Rows[i][j].ToString() + Convert.ToChar();
}
objStreamWriter.WriteLine(strLine);
strLine = "";
}
objStreamWriter.Close();
objFileStream.Close(); //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
//Workbook xlbook = xlapp.Workbooks.Add(true);
//Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
//Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
//range.EntireColumn.AutoFit();
//xlapp.Quit();
return true;
}
}

三、导出GridView到Excel

//导出GridView到Excel中的关键之处
//用法: ToExcel(GVStaff, TextBox1.Text);

public static void ToExcel(System.Web.UI.Control ctl,string FileName)
{
HttpContext.Current.Response.Charset ="UTF-8";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
ctl.Page.EnableViewState =false;
System.IO.StringWriter tw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
} 必须有下面这句!否则不会通过!
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for
}

四、DataTable导出到Excel

public class DataTableToExcel
{
private DataTableToExcel()
{ }
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dt">要导出的DataTable</param>
public static void ExportToExcel(System.Data.DataTable dt )
{
if (dt == null) return; Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
// lblMsg.Text = "无法创建Excel对象,可能您的电脑未安装Excel";
MessageBox.Show( "无法创建Excel对象,可能您的电脑未安装Excel" );
return;
}
System.Windows.Forms.SaveFileDialog saveDia = new SaveFileDialog();
saveDia.Filter = "Excel|*.xls";
saveDia.Title = "导出为Excel文件";
if(saveDia.ShowDialog()== System.Windows.Forms.DialogResult.OK
&& !string.Empty.Equals(saveDia.FileName))
{
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[];//取得sheet1
Microsoft.Office.Interop.Excel.Range range = null;
long totalCount = dt.Rows.Count;
long rowRead = ;
float percent = ;
string fileName = saveDia.FileName;
//写入标题
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[, i + ] = dt.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[, i + ];
//range.Interior.ColorIndex = 15;//背景颜色
range.Font.Bold = true;//粗体
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中
//加边框
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
//range.ColumnWidth = 4.63;//设置列宽
//range.EntireColumn.AutoFit();//自动调整列宽
//r1.EntireRow.AutoFit();//自动调整行高
}
//写入内容
for (int r = ; r < dt.DefaultView.Count; r++)
{
for (int i = ; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + , i + ] = dt.DefaultView[r][i];
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + , i + ];
range.Font.Size = ;//字体大小
//加边框
range.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin, Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, null);
range.EntireColumn.AutoFit();//自动调整列宽
}
rowRead++;
percent = ((float)( * rowRead)) / totalCount;
System.Windows.Forms.Application.DoEvents();
}
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
if (dt.Columns.Count > )
{
range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
}
try
{
workbook.Saved = true;
workbook.SaveCopyAs(fileName);
}
catch (Exception ex)
{
//lblMsg.Text = "导出文件时出错,文件可能正被打开!\n" + ex.Message;
MessageBox.Show( "导出文件时出错,文件可能正被打开!\n" + ex.Message );
return;
} workbooks.Close();
if (xlApp != null)
{
xlApp.Workbooks.Close();
xlApp.Quit();
int generation = System.GC.GetGeneration(xlApp);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
System.GC.Collect(generation);
}
GC.Collect();//强行销毁
#region 强行杀死最近打开的Excel进程
System.Diagnostics.Process[] excelProc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
System.DateTime startTime = new DateTime();
int m, killId = ;
for (m = ; m < excelProc.Length; m++)
{
if (startTime < excelProc[m].StartTime)
{
startTime = excelProc[m].StartTime;
killId = m;
}
}
if (excelProc[killId].HasExited == false)
{
excelProc[killId].Kill();
}
#endregion
MessageBox.Show( "导出成功!" );
}
}
}

五、DataTable导出到excel(2)

StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter( stringWriter );
DataGrid excel = new DataGrid();
System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle headerStyle = new TableItemStyle();
System.Web.UI.WebControls.TableItemStyle itemStyle = new TableItemStyle();
AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
headerStyle.BackColor =System.Drawing.Color.LightGray;
headerStyle.Font.Bold = true;
headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;; excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
excel.HeaderStyle.MergeWith(headerStyle);
excel.ItemStyle.MergeWith(itemStyle);
excel.GridLines = GridLines.Both;
excel.HeaderStyle.Font.Bold = true;
excel.DataSource = dt.DefaultView;//输出DataTable的内容
excel.DataBind();
excel.RenderControl(htmlWriter); string filestr = "d:\\data\\"+filePath; //filePath是文件的路径
int pos = filestr.LastIndexOf( "\\");
string file = filestr.Substring(,pos);
if( !Directory.Exists( file ) )
{
Directory.CreateDirectory(file);
}
System.IO.StreamWriter sw = new StreamWriter(filestr);
sw.Write(stringWriter.ToString());
sw.Close();

C#数据导出到Excel源代码的更多相关文章

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

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

  2. 将C1Chart数据导出到Excel

    大多数情况下,当我们说将图表导出到Excel时,意思是将Chart当成图片导出到Excel中.如果是这样,你可以参考帮助文档中保存和导出C1Chart章节. 不过,也有另一种情况,当你想把图表中的数据 ...

  3. vb.net-三种将datagridview数据导出为excel文件的函数

    第一种方法较慢,但是数据格式都比较好,需要引用excel的 Microsoft.Office.Interop.Excel.dll  office.dll #Region "导出excel函数 ...

  4. 数据导出至Excel文件--好库编程网http://code1.okbase.net/codefile/SerializeHelper.cs_2012122018724_118.htm

    using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; ...

  5. 数据导出到Excel中

    自己修改后的一个数据导出到Excel的方法,粘出来与大家共享. 只需要将             System.Web.HttpContext.Current.Response.Charset =   ...

  6. asp.net将数据导出到excel

    本次应用datatable导出,若用gridview(假设gridview设为了分页显示)会出现只导出当前页的情况. protected void btnPrn_Click(object sender ...

  7. 将datagrid中数据导出到excel中 -------<<工作日志2014-6-6>>

    前台datagrid数据绑定 #region 导出到excel中    /// <summary>    /// 2014-6-6    /// </summary>    / ...

  8. 机房收费系统——在VB中将MSHFlexGrid控件中的数据导出到Excel

    机房收费系统中,好多查询的窗体都包含同一个功能:将数据库中查询到的数据显示在MSHFlexGrid控件中,然后再把MSHFlexGrid控件中的数据导出到Excel表格中. 虽然之前做过学生信息管理系 ...

  9. Qt中将QTableView中的数据导出为Excel文件

    如果你在做一个报表类的程序,可能将内容导出为Excel文件是一项必须的功能.之前使用MFC的时候我就写过一个类,用于将grid中的数据导出为Excel文件.在使用了QtSql模块后,我很容易的将这个类 ...

随机推荐

  1. 汇编笔记 CALL(1)

    assume cs:code code segment start: mov ax, ;将AX通用寄存器设0 call s inc ax s: pop ax ;将数据从桟中取出 code ends e ...

  2. java 学习汇总

    一.安装svn 插件 1.svn - http://subclipse.tigris.org/update 安装的过程中可能出错,解决方法: 导航到:The Eclipse Project Updat ...

  3. 《Advanced Bash-scripting Guide》学习(八):从一个目录移动整个目录树到另一个目录

    本文所选的例子来自于<Advanced Bash-scripting Gudie>一书,译者 杨春敏 黄毅 ABS书上的例子: 从一个目录移动整个目录树到另一个目录 #!/bin/bash ...

  4. c# 打开第三方软件(如:电脑自带看图软件)

    嘿嘿,直接上示例代码 /// <summary> /// 利用第三方软件浏览加工图纸 /// </summary> /// <param name="fileP ...

  5. SSM整合(spring、springMVC、mybatis)

    需要用的包: 包括:spring的包.springMVC的包.mybatis的包.数据库驱动包.json相关的包 配置如下,首先是mybatis的配置 <?xml version="1 ...

  6. 【WPF】命令系统

    引言 在MVVM模式开发下,命令Command是编程中不可或缺的一部分.下面,我分3种场景简单介绍一下命令的用法. ViewModel中的命令 在ViewModel定义命令是最常用的用法,开发中几乎9 ...

  7. python 百题计划

    一.基础篇 想要像类似执行shell脚本一样执行Python脚本,需要在py文件开头加上什么?KEY:#!/usr/bin/env python Python解释器在加载 .py 文件中的代码时,会对 ...

  8. 28 python 并发编程之多进程

    一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程.P ...

  9. STL空间配置器解析和实现

    STL空间配置器的强大和借鉴作用不言而喻,查阅资料,发现了Dawn_sf已经对其有了极其深入和详细的描述,所以决定偷下懒借用其内容,只提供自己实现STL空间配置器的源码,具体解析内容参考:(一)STL ...

  10. MySQL实战 | 03 - 谁动了我的数据:浅析MySQL的事务隔离级别

    原文链接:这一次,带你搞清楚MySQL的事务隔离级别! 使用过关系型数据库的,应该都事务的概念有所了解,知道事务有 ACID 四个基本属性:原子性(Atomicity).一致性(Consistency ...