分享
 
 
 

DataGrid的数据导入到Excel或CSV

王朝other·作者佚名  2006-03-08
窄屏简体版  字體: |||超大  

这几天一直在给我姐姐公司的开发一个新的软件,方便他们使用。这个软件使用C#+Sql Server建设的,基本上算是完成了,但是今天他们提出了一个功能数据的导出功能,我在网上搜索了一下,再CodePorject发现了RKLib的导入导出的源码。

在导出中文数据时,出现了乱码,大致看了一下估计是数据写入的时候得编码问题,所以就想到了编码更改。所以就更改了一个代码,结果果然实现了支持的中文的导出。

RKLib.Export源码:

// ---------------------------------------------------------

// Rama Krishna's Export class

// Copyright (C) 2004 Rama Krishna. All rights reserved.

// ---------------------------------------------------------

# region Includes...

using System;

using System.Data;

using System.Web;

using System.Web.SessionState;

using System.IO;

using System.Text;

using System.Xml;

using System.Xml.Xsl;

using System.Threading;

# endregion // Includes...

namespace LetBetter

{

# region Summary

/// <summary>

/// Exports datatable to CSV or Excel format.

/// This uses DataSet's XML features and XSLT for exporting.

///

/// C#.Net Example to be used in WebForms

/// -------------------------------------

/// using MyLib.ExportData;

///

/// private void btnExport_Click(object sender, System.EventArgs e)

/// {

/// try

/// {

/// // Declarations

/// DataSet dsUsers = ((DataSet) Session["dsUsers"]).Copy( );

/// MyLib.ExportData.Export oExport = new MyLib.ExportData.Export("Web");

/// string FileName = "UserList.csv";

/// int[] ColList = {2, 3, 4, 5, 6};

/// oExport.ExportDetails(dsUsers.Tables[0], ColList, Export.ExportFormat.CSV, FileName);

/// }

/// catch(Exception Ex)

/// {

/// lblError.Text = Ex.Message;

/// }

/// }

///

/// VB.Net Example to be used in WindowsForms

/// -----------------------------------------

/// Imports MyLib.ExportData

///

/// Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

///

/// Try

///

/// 'Declarations

/// Dim dsUsers As DataSet = (CType(Session("dsUsers"), DataSet)).Copy()

/// Dim oExport As New MyLib.ExportData.Export("Win")

/// Dim FileName As String = "C:\\UserList.xls"

/// Dim ColList() As Integer = New Integer() {2, 3, 4, 5, 6}

/// oExport.ExportDetails(dsUsers.Tables(0), ColList, Export.ExportFormat.CSV, FileName)

///

/// Catch Ex As Exception

/// lblError.Text = Ex.Message

/// End Try

///

/// End Sub

///

/// </summary>

# endregion // Summary

public class Export

{

public enum ExportFormat : int {CSV = 1, Excel = 2}; // Export format enumeration

System.Web.HttpResponse response;

private string appType;

public Export()

{

appType = "Web";

response = System.Web.HttpContext.Current.Response;

}

public Export(string ApplicationType)

{

appType = ApplicationType;

if(appType != "Web" && appType != "Win") throw new Exception("Provide valid application format (Web/Win)");

if (appType == "Web") response = System.Web.HttpContext.Current.Response;

}

#region ExportDetails OverLoad : Type#1

// Function : ExportDetails

// Arguments : DetailsTable, FormatType, FileName

// Purpose : To get all the column headers in the datatable and

// exports in CSV / Excel format with all columns

public void ExportDetails(DataTable DetailsTable, ExportFormat FormatType, string FileName)

{

try

{

if(DetailsTable.Rows.Count == 0)

throw new Exception("There are no details to export.");

// Create Dataset

DataSet dsExport = new DataSet("Export");

DataTable dtExport = DetailsTable.Copy();

dtExport.TableName = "Values";

dsExport.Tables.Add(dtExport);

// Getting Field Names

string[] sHeaders = new string[dtExport.Columns.Count];

string[] sFileds = new string[dtExport.Columns.Count];

for (int i=0; i < dtExport.Columns.Count; i++)

{

sHeaders[i] = dtExport.Columns[i].ColumnName;

sFileds[i] = dtExport.Columns[i].ColumnName;

}

if(appType == "Web")

Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);

else if(appType == "Win")

Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // ExportDetails OverLoad : Type#1

#region ExportDetails OverLoad : Type#2

// Function : ExportDetails

// Arguments : DetailsTable, ColumnList, FormatType, FileName

// Purpose : To get the specified column headers in the datatable and

// exorts in CSV / Excel format with specified columns

public void ExportDetails(DataTable DetailsTable, int[] ColumnList, ExportFormat FormatType, string FileName)

{

try

{

if(DetailsTable.Rows.Count == 0)

throw new Exception("There are no details to export");

// Create Dataset

DataSet dsExport = new DataSet("Export");

DataTable dtExport = DetailsTable.Copy();

dtExport.TableName = "Values";

dsExport.Tables.Add(dtExport);

if(ColumnList.Length > dtExport.Columns.Count)

throw new Exception("ExportColumn List should not exceed Total Columns");

// Getting Field Names

string[] sHeaders = new string[ColumnList.Length];

string[] sFileds = new string[ColumnList.Length];

for (int i=0; i < ColumnList.Length; i++)

{

if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))

throw new Exception("ExportColumn Number should not exceed Total Columns Range");

sHeaders[i] = dtExport.Columns[ColumnList[i]].ColumnName;

sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;

}

if(appType == "Web")

Export_with_XSLT_Web(dsExport, sHeaders, sFileds, FormatType, FileName);

else if(appType == "Win")

Export_with_XSLT_Windows(dsExport, sHeaders, sFileds, FormatType, FileName);

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // ExportDetails OverLoad : Type#2

#region ExportDetails OverLoad : Type#3

// Function : ExportDetails

// Arguments : DetailsTable, ColumnList, Headers, FormatType, FileName

// Purpose : To get the specified column headers in the datatable and

// exorts in CSV / Excel format with specified columns and

// with specified headers

public void ExportDetails(DataTable DetailsTable, int[] ColumnList, string[] Headers, ExportFormat FormatType,

string FileName)

{

try

{

if(DetailsTable.Rows.Count == 0)

throw new Exception("There are no details to export");

// Create Dataset

DataSet dsExport = new DataSet("Export");

DataTable dtExport = DetailsTable.Copy();

dtExport.TableName = "Values";

dsExport.Tables.Add(dtExport);

if(ColumnList.Length != Headers.Length)

throw new Exception("ExportColumn List and Headers List should be of same length");

else if(ColumnList.Length > dtExport.Columns.Count || Headers.Length > dtExport.Columns.Count)

throw new Exception("ExportColumn List should not exceed Total Columns");

// Getting Field Names

string[] sFileds = new string[ColumnList.Length];

for (int i=0; i < ColumnList.Length; i++)

{

if((ColumnList[i] < 0) || (ColumnList[i] >= dtExport.Columns.Count))

throw new Exception("ExportColumn Number should not exceed Total Columns Range");

sFileds[i] = dtExport.Columns[ColumnList[i]].ColumnName;

}

if(appType == "Web")

Export_with_XSLT_Web(dsExport, Headers, sFileds, FormatType, FileName);

else if(appType == "Win")

Export_with_XSLT_Windows(dsExport, Headers, sFileds, FormatType, FileName);

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // ExportDetails OverLoad : Type#3

#region Export_with_XSLT_Web

// Function : Export_with_XSLT_Web

// Arguments : dsExport, sHeaders, sFileds, FormatType, FileName

// Purpose : Exports dataset into CSV / Excel format

private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)

{

try

{

// Appending Headers

response.Clear();

response.Buffer= true;

if(FormatType == ExportFormat.CSV)

{

response.ContentType = "text/csv";

response.AppendHeader("content-disposition", "attachment; filename=" + FileName);

}

else

{

response.ContentType = "application/vnd.ms-excel";

response.AppendHeader("content-disposition", "attachment; filename=" + FileName);

}

// XSLT to use for transforming this dataset.

MemoryStream stream = new MemoryStream( );

XmlTextWriter writer = new XmlTextWriter(stream, new System.Text.UnicodeEncoding());

CreateStylesheet(writer, sHeaders, sFileds, FormatType);

writer.Flush( );

stream.Seek( 0, SeekOrigin.Begin);

XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);

XslTransform xslTran = new XslTransform();

xslTran.Load(new XmlTextReader(stream), null, null);

System.IO.StringWriter sw = new System.IO.StringWriter();

xslTran.Transform(xmlDoc, null, sw, null);

//Writeout the Content

response.Write(sw.ToString());

sw.Close();

writer.Close();

stream.Close();

response.End();

}

catch(ThreadAbortException Ex)

{

string ErrMsg = Ex.Message;

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // Export_with_XSLT

#region Export_with_XSLT_Windows

// Function : Export_with_XSLT_Windows

// Arguments : dsExport, sHeaders, sFileds, FormatType, FileName

// Purpose : Exports dataset into CSV / Excel format

private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)

{

try

{

// XSLT to use for transforming this dataset.

MemoryStream stream = new MemoryStream( );

XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.GetEncoding("gb2312"));

CreateStylesheet(writer, sHeaders, sFileds, FormatType);

writer.Flush( );

stream.Seek( 0, SeekOrigin.Begin);

XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);

XslTransform xslTran = new XslTransform();

xslTran.Load(new XmlTextReader(stream), null, null);

System.IO.StringWriter sw = new System.IO.StringWriter();

xslTran.Transform(xmlDoc, null, sw, null);

//Writeout the Content

// StreamWriter strwriter = new StreamWriter(FileName);

StreamWriter strwriter=new StreamWriter(FileName,false,System.Text.Encoding.GetEncoding("gb2312"));

strwriter.WriteLine(sw.ToString());

strwriter.Close();

sw.Close();

writer.Close();

stream.Close();

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // Export_with_XSLT

#region CreateStylesheet

// Function : WriteStylesheet

// Arguments : writer, sHeaders, sFileds, FormatType

// Purpose : Creates XSLT file to apply on dataset's XML file

private void CreateStylesheet(XmlTextWriter writer, string[] sHeaders, string[] sFileds, ExportFormat FormatType)

{

try

{

// xsl:stylesheet

string ns = "http://www.w3.org/1999/XSL/Transform";

writer.Formatting = Formatting.Indented;

writer.WriteStartDocument( );

writer.WriteStartElement("xsl","stylesheet",ns);

writer.WriteAttributeString("version","1.0");

writer.WriteStartElement("xsl:output");

writer.WriteAttributeString("method","text");

writer.WriteAttributeString("version","4.0");

writer.WriteEndElement( );

// xsl-template

writer.WriteStartElement("xsl:template");

writer.WriteAttributeString("match","/");

// xsl:value-of for headers

for(int i=0; i< sHeaders.Length; i++)

{

writer.WriteString("\"");

writer.WriteStartElement("xsl:value-of");

writer.WriteAttributeString("select", "'" + sHeaders[i] + "'");

writer.WriteEndElement( ); // xsl:value-of

writer.WriteString("\"");

if (i != sFileds.Length - 1) writer.WriteString( (FormatType == ExportFormat.CSV ) ? "," : " " );

}

// xsl:for-each

writer.WriteStartElement("xsl:for-each");

writer.WriteAttributeString("select","Export/Values");

writer.WriteString("\r\n");

// xsl:value-of for data fields

for(int i=0; i< sFileds.Length; i++)

{

writer.WriteString("\"");

writer.WriteStartElement("xsl:value-of");

writer.WriteAttributeString("select", sFileds[i]);

writer.WriteEndElement( ); // xsl:value-of

writer.WriteString("\"");

if (i != sFileds.Length - 1) writer.WriteString( (FormatType == ExportFormat.CSV ) ? "," : " " );

}

writer.WriteEndElement( ); // xsl:for-each

writer.WriteEndElement( ); // xsl-template

writer.WriteEndElement( ); // xsl:stylesheet

writer.WriteEndDocument( );

}

catch(Exception Ex)

{

throw Ex;

}

}

#endregion // WriteStylesheet

}

}

在winform下的工程,如果需要中文支持,只需要更改一行代码即可:

将Export_with_XSLT_Windows函数中的:

StreamWriter strwriter = new StreamWriter(FileName);

更改为:

StreamWriter strwriter=new StreamWriter(FileName,false,System.Text.Encoding.GetEncoding("gb2312"));

即可。

嘿嘿,很简单吧!

不过需要注意的是:

1、在使用此代码时,需要在工程中添加对System.Web的引用;

2、此代码在执行数据导出时,速度比较慢。我想在下一个版本中,使用我没有以前没有使用过的多线程操作,也许这样可以更改一下速度。(每次工程都要对自己提出挑战)

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有