【C# winfrom】datagrid导出为excel、html、xml、xslt源码123
来源:百度文库 编辑:神马文学网 时间:2024/04/29 10:48:03
转自:江边孤鸟 http://blog.csdn.net/jbgh608/
1、添加Excel引用
2、编写导出方法
using System;
using System.Windows.Forms;
using System.Diagnostics;
using XcjwHIS.PubicBaseClasses;
using System.Data;
using System.IO;
using System.Xml;
using System.Text;
namespace 江边孤鸟 http://blog.csdn.net/jbgh608/
...{
/**////
/// DataGrid、报表 导出为Excel文件,XML文件
/// add by hxc20070830 who‘s email is jbgh608@163.com
///
public class ExportDataGrid
...{
/**////
/// 源DataGrid
///
private DataGrid ExportGrid;
/**////
/// 调用窗口
///
private Form ParentWindow=null;
private DataTable mytb;
/**////
/// DataGrid 导出 Excel文件
///
/// 父亲窗口
/// 要导出的DataGrid
public ExportDataGrid(Form parentWindow,DataGrid grid)
...{
ExportGrid=grid;
ParentWindow= parentWindow;
}
/**////
/// 报表导出为Excel文件
///
/// 父亲窗口
/// 数据源
public ExportDataGrid(Form parentWindow,DataSet ds)
...{
mytb=ds.Tables[0].Copy();
ParentWindow= parentWindow;
}
保存对话框#region 保存对话框
/**////
/// 导出文件
///
/// 文件类型 1 Excel ;2 xml and html
public void SaveFileDialog(int ExportType)
...{
string localFilePath,fileNameExt,newFileName,FilePath;
SaveFileDialog sfd = new SaveFileDialog ( ) ;
sfd.AddExtension=true;
sfd.Filter= " txt files(*.xls)|*.xls|All files(*.*)|*.*" ;
sfd.FilterIndex = 2 ;
sfd.RestoreDirectory = true ;
if ( sfd.ShowDialog ( ) == DialogResult.OK )
...{
localFilePath=sfd.FileName.ToString();
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\") + 1);
FilePath= localFilePath.Substring(0,localFilePath.LastIndexOf("\") );
newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
this.ParentWindow.Cursor=new Cursor(Constant.ApplicationDirectory+"\wait.cur");
//this.ParentWindow.Cursor=PublicStaticFun.GetCursor("Xc_db_rygl.wait.cur",GetType());
switch( ExportType)
...{
//江边孤鸟 http://blog.csdn.net/jbgh608/
case 1:
ExportExcel(FilePath+"\"+newFileName,fileNameExt);
break;
case 2:
ExportHtml( FilePath+"\"+newFileName,fileNameExt);
ExportXslt(fileNameExt);
ExportXml(FilePath+"\"+newFileName,fileNameExt);
break;
}
}
}
#endregion
导出Excel#region 导出Excel
/**////
/// 导出Excel
///
/// 文件路径
/// 表头
///
public bool ExportExcel(string FilePath,string p_ReportName)
...{
if ( this.ExportGrid.TableStyles.Count == 0 ) return false;
DataGridTableStyle ts = this.ExportGrid.TableStyles[0];
// 创建Excel对象
Excel.Application xlApp = new Excel.ApplicationClass();
if ( xlApp == null )
...{
MessageBox.Show("Excel无法启动");
return false;
}
// 创建Excel工作薄
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
// 设置标题
Excel.Range range = xlSheet.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,ts.GridColumnStyles.Count]);
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = p_ReportName;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;
// 列索引,行索引,总列数,总行数
int colIndex = 0;
int RowIndex = 0;
int colCount = ts.GridColumnStyles.Count;
int RowCount = this.ParentWindow.BindingContext[this.ExportGrid.DataSource,this.ExportGrid.DataMember].Count;
// 创建缓存数据
object[,] objData = new object[RowCount + 1, colCount ];
// 获取列标题
foreach(DataGridColumnStyle cs in ts.GridColumnStyles)
...{
objData[RowIndex,colIndex++] = cs.HeaderText;
}
// 获取数据
for(RowIndex =1;RowIndex<=RowCount;RowIndex++)
...{
for(colIndex=0;colIndex < colCount;colIndex++)
...{
objData[RowIndex,colIndex] = this.ExportGrid[RowIndex-1,colIndex].ToString();
}
Application.DoEvents();
}
// 写入Excel
xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colIndex]).Font.Bold = true;
range = xlSheet.get_Range(xlApp.Cells[2,1],xlApp.Cells[RowCount+2,colCount]);
range.Value2 = objData;
// 保存
try
...{
xlApp.Cells.EntireColumn.AutoFit();
xlApp.Cells.VerticalAlignment = Excel.Constants.xlCenter;
xlApp.Cells.HorizontalAlignment = Excel.Constants.xlCenter;
//xlApp.Visible = true;
xlBook.Saved = true;
xlBook.SaveCopyAs(FilePath + ".xls");
}
catch
...{
MessageBox.Show("保存出错,请检查!");
return false;
}
finally
...{
xlApp.Quit();
GC.Collect();
KillProcess("excel") ;
this.ParentWindow.Cursor=Cursors.Default;
}
return true;
}
#endregion
杀死进程#region 杀死进程
private void KillProcess(string processName)
...{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打开的进程
try
...{
foreach (Process thisproc in Process.GetProcessesByName(processName))
...{
thisproc.Kill();
}
}
catch(Exception Exc)
...{
throw new Exception("",Exc);
}
}
#endregion
导出Xml#region 导出Xml
/**////
/// datagrid导出xml
///
/// 保存路径
/// 文件名称
///
private bool ExportXml(string FilePath,string p_ReportName)
...{
string path=Constant.ApplicationDirectory+"\xml\"+p_ReportName+".xslt";
string PItext ="type=‘text/xsl‘ href=‘"+path+"‘";
DataSet ds=new DataSet();
try
...{
DataTable tb = (DataTable)this.ExportGrid.DataSource;
DataTable ExportTb=tb.Copy();
ds.Tables.Add(ExportTb);
XmlTextReader XTReader = new XmlTextReader(ds.GetXml(),XmlNodeType.Element,null);
XmlTextWriter XTWriter = new XmlTextWriter(FilePath+".xml",Encoding.UTF8);
XTWriter.WriteStartDocument();
XTWriter.WriteProcessingInstruction("xml-stylesheet",PItext);
string fieldName = "" ;
while(XTReader.Read())
...{
switch(XTReader.NodeType)
...{
case XmlNodeType.Element:
XTWriter.WriteStartElement(XTReader.Name);
fieldName = XTReader.Name;
break;
case XmlNodeType.Text:
if(fieldName.ToLower() == "brithday"||fieldName.ToLower() == "gzsj"||fieldName.ToLower() == "rdsj"||fieldName.ToLower() == "zzsj")
...{
DateTime dt = DateTime.Parse (XTReader.Value.ToString());
XTWriter.WriteString(dt.ToString("yyyy-MM-dd"));
}
else
XTWriter.WriteString(XTReader.Value);
break;
case XmlNodeType.EndElement:
XTWriter.WriteEndElement();
break;
default:
break;
}
}
XTWriter.Close();
this.ParentWindow.Cursor=Cursors.Default;
}
catch
...{
MessageBox.Show("保存出错,请检查!");
return false;
}
finally
...{
//GC.Collect();
//ds.Clear();
//ds.Dispose();
}
return true;
}
#endregion
导出Xslt#region 导出Xslt
/**////
/// 导出xslt样式
///
/// 文件名称
private void ExportXslt( string p_ReportName )
...{
DataGrid d=this.ExportGrid;
string fileName=Constant.ApplicationDirectory+"\xml\"+p_ReportName+".xslt";
string title =p_ReportName;
string s1=" ";
string s2=" ";
string s3=" "+title+"
string s4="
";
try
...{
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s5 += "" + gc.HeaderText + " ";
}
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s7 += " ";
}
string sXslt=s1+s2+s3+s4+s5+s6+s7+s8;
Stream stream =File.OpenWrite(fileName);
using(StreamWriter writer =new StreamWriter(stream))
...{
writer.Write(sXslt);
}
}
catch(Exception e)
...{
MessageBox.Show(e.Message+" "+e.StackTrace+" "+e.Source);
}
}
#endregion
导出html#region 导出html
/**////
/// datagrid导出html
///
/// 保存路径
/// 名称
public void ExportHtml( string FilePath,string p_ReportName)
...{
DataGrid d =this.ExportGrid;
DataTable dt = d.DataSource as DataTable;
string path =FilePath+".html";
string title =p_ReportName;
string s1 = "" + title ;
string s2 = " " + "";
";
if( dt == null || dt.Rows.Count == 0 ) return;
int len = d.TableStyles[0].GridColumnStyles.Count;
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s2 += "" + gc.HeaderText + " ";
}
foreach( DataRow dr in dt.Rows )
...{
s3 += "";
for( int i = 0; i < len; i ++ )
...{
s3 += "" + dr[ i ].ToString() + " ";
}
s3 += " ";
}
string s = s1 + s2 + s3 + s4;
try
...{
using( FileStream fs = File.Create( path ) )
...{
using( StreamWriter sw = new StreamWriter( fs ) )
...{
sw.Write( s );
}
}
}
catch( Exception ex )
...{
MessageBox.Show( ex.Message + " " + ex.StackTrace + " " + ex.Source );
}
}
#endregion
}
}
1、添加Excel引用
2、编写导出方法
using System;
using System.Windows.Forms;
using System.Diagnostics;
using XcjwHIS.PubicBaseClasses;
using System.Data;
using System.IO;
using System.Xml;
using System.Text;
namespace 江边孤鸟 http://blog.csdn.net/jbgh608/
...{
/**////
/// DataGrid、报表 导出为Excel文件,XML文件
/// add by hxc20070830 who‘s email is jbgh608@163.com
///
public class ExportDataGrid
...{
/**////
/// 源DataGrid
///
private DataGrid ExportGrid;
/**////
/// 调用窗口
///
private Form ParentWindow=null;
private DataTable mytb;
/**////
/// DataGrid 导出 Excel文件
///
/// 父亲窗口
/// 要导出的DataGrid
public ExportDataGrid(Form parentWindow,DataGrid grid)
...{
ExportGrid=grid;
ParentWindow= parentWindow;
}
/**////
/// 报表导出为Excel文件
///
/// 父亲窗口
/// 数据源
public ExportDataGrid(Form parentWindow,DataSet ds)
...{
mytb=ds.Tables[0].Copy();
ParentWindow= parentWindow;
}
保存对话框#region 保存对话框
/**////
/// 导出文件
///
/// 文件类型 1 Excel ;2 xml and html
public void SaveFileDialog(int ExportType)
...{
string localFilePath,fileNameExt,newFileName,FilePath;
SaveFileDialog sfd = new SaveFileDialog ( ) ;
sfd.AddExtension=true;
sfd.Filter= " txt files(*.xls)|*.xls|All files(*.*)|*.*" ;
sfd.FilterIndex = 2 ;
sfd.RestoreDirectory = true ;
if ( sfd.ShowDialog ( ) == DialogResult.OK )
...{
localFilePath=sfd.FileName.ToString();
fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\") + 1);
FilePath= localFilePath.Substring(0,localFilePath.LastIndexOf("\") );
newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;
this.ParentWindow.Cursor=new Cursor(Constant.ApplicationDirectory+"\wait.cur");
//this.ParentWindow.Cursor=PublicStaticFun.GetCursor("Xc_db_rygl.wait.cur",GetType());
switch( ExportType)
...{
//江边孤鸟 http://blog.csdn.net/jbgh608/
case 1:
ExportExcel(FilePath+"\"+newFileName,fileNameExt);
break;
case 2:
ExportHtml( FilePath+"\"+newFileName,fileNameExt);
ExportXslt(fileNameExt);
ExportXml(FilePath+"\"+newFileName,fileNameExt);
break;
}
}
}
#endregion
导出Excel#region 导出Excel
/**////
/// 导出Excel
///
/// 文件路径
/// 表头
///
public bool ExportExcel(string FilePath,string p_ReportName)
...{
if ( this.ExportGrid.TableStyles.Count == 0 ) return false;
DataGridTableStyle ts = this.ExportGrid.TableStyles[0];
// 创建Excel对象
Excel.Application xlApp = new Excel.ApplicationClass();
if ( xlApp == null )
...{
MessageBox.Show("Excel无法启动");
return false;
}
// 创建Excel工作薄
Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
// 设置标题
Excel.Range range = xlSheet.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,ts.GridColumnStyles.Count]);
range.MergeCells = true;
xlApp.ActiveCell.FormulaR1C1 = p_ReportName;
xlApp.ActiveCell.Font.Size = 20;
xlApp.ActiveCell.Font.Bold = true;
xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;
// 列索引,行索引,总列数,总行数
int colIndex = 0;
int RowIndex = 0;
int colCount = ts.GridColumnStyles.Count;
int RowCount = this.ParentWindow.BindingContext[this.ExportGrid.DataSource,this.ExportGrid.DataMember].Count;
// 创建缓存数据
object[,] objData = new object[RowCount + 1, colCount ];
// 获取列标题
foreach(DataGridColumnStyle cs in ts.GridColumnStyles)
...{
objData[RowIndex,colIndex++] = cs.HeaderText;
}
// 获取数据
for(RowIndex =1;RowIndex<=RowCount;RowIndex++)
...{
for(colIndex=0;colIndex < colCount;colIndex++)
...{
objData[RowIndex,colIndex] = this.ExportGrid[RowIndex-1,colIndex].ToString();
}
Application.DoEvents();
}
// 写入Excel
xlApp.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colIndex]).Font.Bold = true;
range = xlSheet.get_Range(xlApp.Cells[2,1],xlApp.Cells[RowCount+2,colCount]);
range.Value2 = objData;
// 保存
try
...{
xlApp.Cells.EntireColumn.AutoFit();
xlApp.Cells.VerticalAlignment = Excel.Constants.xlCenter;
xlApp.Cells.HorizontalAlignment = Excel.Constants.xlCenter;
//xlApp.Visible = true;
xlBook.Saved = true;
xlBook.SaveCopyAs(FilePath + ".xls");
}
catch
...{
MessageBox.Show("保存出错,请检查!");
return false;
}
finally
...{
xlApp.Quit();
GC.Collect();
KillProcess("excel") ;
this.ParentWindow.Cursor=Cursors.Default;
}
return true;
}
#endregion
杀死进程#region 杀死进程
private void KillProcess(string processName)
...{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有打开的进程
try
...{
foreach (Process thisproc in Process.GetProcessesByName(processName))
...{
thisproc.Kill();
}
}
catch(Exception Exc)
...{
throw new Exception("",Exc);
}
}
#endregion
导出Xml#region 导出Xml
/**////
/// datagrid导出xml
///
/// 保存路径
/// 文件名称
///
private bool ExportXml(string FilePath,string p_ReportName)
...{
string path=Constant.ApplicationDirectory+"\xml\"+p_ReportName+".xslt";
string PItext ="type=‘text/xsl‘ href=‘"+path+"‘";
DataSet ds=new DataSet();
try
...{
DataTable tb = (DataTable)this.ExportGrid.DataSource;
DataTable ExportTb=tb.Copy();
ds.Tables.Add(ExportTb);
XmlTextReader XTReader = new XmlTextReader(ds.GetXml(),XmlNodeType.Element,null);
XmlTextWriter XTWriter = new XmlTextWriter(FilePath+".xml",Encoding.UTF8);
XTWriter.WriteStartDocument();
XTWriter.WriteProcessingInstruction("xml-stylesheet",PItext);
string fieldName = "" ;
while(XTReader.Read())
...{
switch(XTReader.NodeType)
...{
case XmlNodeType.Element:
XTWriter.WriteStartElement(XTReader.Name);
fieldName = XTReader.Name;
break;
case XmlNodeType.Text:
if(fieldName.ToLower() == "brithday"||fieldName.ToLower() == "gzsj"||fieldName.ToLower() == "rdsj"||fieldName.ToLower() == "zzsj")
...{
DateTime dt = DateTime.Parse (XTReader.Value.ToString());
XTWriter.WriteString(dt.ToString("yyyy-MM-dd"));
}
else
XTWriter.WriteString(XTReader.Value);
break;
case XmlNodeType.EndElement:
XTWriter.WriteEndElement();
break;
default:
break;
}
}
XTWriter.Close();
this.ParentWindow.Cursor=Cursors.Default;
}
catch
...{
MessageBox.Show("保存出错,请检查!");
return false;
}
finally
...{
//GC.Collect();
//ds.Clear();
//ds.Dispose();
}
return true;
}
#endregion
导出Xslt#region 导出Xslt
/**////
/// 导出xslt样式
///
/// 文件名称
private void ExportXslt( string p_ReportName )
...{
DataGrid d=this.ExportGrid;
string fileName=Constant.ApplicationDirectory+"\xml\"+p_ReportName+".xslt";
string title =p_ReportName;
string s1=" ";
string s2="
string s3="
"+title+"
";string s4="
try
...{
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s5 += "
}
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s7 += "
}
string sXslt=s1+s2+s3+s4+s5+s6+s7+s8;
Stream stream =File.OpenWrite(fileName);
using(StreamWriter writer =new StreamWriter(stream))
...{
writer.Write(sXslt);
}
}
catch(Exception e)
...{
MessageBox.Show(e.Message+" "+e.StackTrace+" "+e.Source);
}
}
#endregion
导出html#region 导出html
/**////
/// datagrid导出html
///
/// 保存路径
/// 名称
public void ExportHtml( string FilePath,string p_ReportName)
...{
DataGrid d =this.ExportGrid;
DataTable dt = d.DataSource as DataTable;
string path =FilePath+".html";
string title =p_ReportName;
string s1 = "
string s2 = "
" +title+"
if( dt == null || dt.Rows.Count == 0 ) return;
int len = d.TableStyles[0].GridColumnStyles.Count;
foreach( DataGridColumnStyle gc in d.TableStyles[0].GridColumnStyles )
...{
s2 += "
}
foreach( DataRow dr in dt.Rows )
...{
s3 += "
for( int i = 0; i < len; i ++ )
...{
s3 += "
}
s3 += "
}
string s = s1 + s2 + s3 + s4;
try
...{
using( FileStream fs = File.Create( path ) )
...{
using( StreamWriter sw = new StreamWriter( fs ) )
...{
sw.Write( s );
}
}
}
catch( Exception ex )
...{
MessageBox.Show( ex.Message + " " + ex.StackTrace + " " + ex.Source );
}
}
#endregion
}
}
【C# winfrom】datagrid导出为excel、html、xml、xslt源码123
XML.com: What is XSLT?
XSLT简介:Google的XML接口的XSLT设计
XSLT轻松入门第一章:XSLT的概念 [XML]
HTML & XML 转义字符
html特效源码收集
C#操作XML简要教程
C#操作XML简要教程
c# 对象序列化为XML
数据库导出xml、htm、csv、sql
c# excel插入空行
C# XML解析方式实例解析
ASP.NET技巧:將datagrid控件內容輸出到excel文件
ASP.NET技巧:將datagrid控件內容輸出到excel文件
把数据用excel导出1(java)
EXCEL必备工具箱--导出工作表功能
html、xhtml与xml的区别
ASP导出excel表格的方法(修改excel文件)
C HTML Parser, HTML Scraper, Convert HTML to well-formed XML
C#发现之旅第一讲 C#-XML开发
将PPT内容导出为JPG图片
用C#快速往Excel写数据
Visual C# 编程操作Excel @阿良.NET
jsp打印,导出word/excel - - JavaEye技术网站