怎样把DataGrid中数据导出成EXCEL。一定要C#的语言来写哈!!!

超人汪 2004-04-02 10:18:42
我翻阅了以前的所有文章,都没找到一个合适我的
孟子E章也没给出C#语言写的代码
谁能提供一个详细点的,马上给分
...全文
117 19 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
中伟视界科技 2004-04-08
  • 打赏
  • 举报
回复
up
kob 2004-04-08
  • 打赏
  • 举报
回复
to lengshuangzi(冷霜子) :
你的方法,如果DataGrid里面有汉字,Excel里面会有乱码
xyz3 2004-04-08
  • 打赏
  • 举报
回复
有没有在c#做过的
tjq_tang 2004-04-03
  • 打赏
  • 举报
回复
http://www.xbee.org/pub/Temp/csharp/DataSetToExcel.txt
caozping 2004-04-02
  • 打赏
  • 举报
回复
public bool TableToExcel(DataTable dt, string fileName, bool showTitle)
{
bool boolResult = false;
System.IO.FileStream fsobj = null;
System.IO.StreamWriter _sw = null;

try
{

fsobj = new FileStream(fileName,System.IO.FileMode.Create,FileAccess.ReadWrite);//生成一个文件流
_sw = new StreamWriter(fsobj,System.Text.UnicodeEncoding.Unicode); //生成一个写入器
//写列标题
if(showTitle)
{
for(int i=0;i<dt.Columns.Count;i++)
{
_sw.Write("'"+dt.Columns[i].ColumnName+"\t");
}
_sw.Write("\r");
}
//写数据
for(int i=0;i<dt.Rows.Count;i++)
{
for(int j=0;j<dt.Columns.Count;j++)
{
_sw.Write(dt.Rows[i][j].ToString().Trim()+((char)2).ToString()+"\t");
}
_sw.Write("\r");
}

_sw.Close();
fsobj.Close();
boolResult = true;
}
catch(Exception er)
{
string a = er.Message;
if(_sw!=null)
{
_sw.Close();
}
if(fsobj!=null)
{
fsobj.Close();
}
boolResult = false;
}

return boolResult;
}
hychieftain 2004-04-02
  • 打赏
  • 举报
回复
to wwwwjjjj1978(风流小太狼)
你的意思是WinForm下的,把你找到的代码用我给你网页下个转化软件就行了
lengshuangzi 2004-04-02
  • 打赏
  • 举报
回复
/*
* 将Grid表格的内容转换为Excel文件
* 使用注意:不能有linkButton之类的列,linkButton将会导致程序寻找别的链接从而引进异常
* */
public static void gridToExcel(System.Web.UI.WebControls.DataGrid grid, string excelName)
{
HttpContext.Current.Response.Charset ="GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=" + excelName + ".xls");
//HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");

grid.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
grid.RenderControl(hw);

HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}
xjliang007 2004-04-02
  • 打赏
  • 举报
回复
good
超人汪 2004-04-02
  • 打赏
  • 举报
回复
我是要在点击一个Button的时候来触发这个事件
超人汪 2004-04-02
  • 打赏
  • 举报
回复
不是asp.net中DataGrid
是.NET中的DataGrid
hychieftain 2004-04-02
  • 打赏
  • 举报
回复
再给你一个VB.NET和C#互转的工具
http://expert.csdn.net/Expert/topic/1645/1645967.xml
hychieftain 2004-04-02
  • 打赏
  • 举报
回复
using System;
using System.Text;
namespace toExcel {

//功能:将asp.net中DataGrid生成Excel文件下载。
//Mountains改进:1、支持中文 2、隐藏列不显示
//日期:2002.10.30
public class DataGridToCSV {

public string GenerateFile(ref System.Web.UI.Page Page, System.Web.UI.WebControls.DataGrid MyDataGrid, string FileName) {

HttpResponse resp;
int colCount = MyDataGrid.Columns.Count - 1;

resp = Page.Response;

resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312") //解决中文乱码之关键;
//resp.Charset = "utf-8"
//resp.AddFileDependency(FileName)
//resp.ContentType = "Text/HTML"
////resp.AppendHeader("Content-Type", "text/html; charset=gb2312")

resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName) //必要,做成下载文件;


string colHeaders = "";
StringBuilder StringBuilder strItems = new StringBuilder();

DataGridColumn myCol;

int i;

for ( i = 0 ; GAIS <= colCount
myCol = MyDataGrid.Columns(i);
if ( myCol.Visible = true ) {
colHeaders = colHeaders + myCol.HeaderText.ToString + ",";
}
} //

if ( colHeaders.Length > 0 ) {
colHeaders = colHeaders.Substring(0, colHeaders.LastIndexOf(","));
}

colHeaders = colHeaders + Chr(13) + Chr(10);


resp.Write(colHeaders);

string colRow;

DataGridItem item;

foreach ( item In MyDataGrid.Items
resp.Write(FormatExportRow(colCount, item, MyDataGrid));
} // item

resp.}();

}

private string FormatExportRow( int colCount, DataGridItem Item, System.Web.UI.WebControls.DataGrid MyDataGrid) {
string strItem;
int i;

for ( i = 0 ; GAIS <= colCount
if ( MyDataGrid.Columns(i).Visible = true ) {
if ( Item.Cells(i).Text Is System.DBNull.value ) {
Item.Cells(i).Text = "";
}
if ( i = colCount ) {
strItem += Item.Cells(i).Text.ToString + Chr(13) + Chr(10);
} else {
strItem += Item.Cells(i).Text.ToString + ",";
}
}
} //
strItem = Replace(strItem, " ", " ");
return strItem;
}


}

}
yuewenbin 2004-04-02
  • 打赏
  • 举报
回复
private void WriteDataGrid2Excel()
{
OWC.SpreadsheetClass xlsheet = new SpreadsheetClass();
this.cn.Open();
SqlCommand cm = new SqlCommand("SELECT * FROM TEST",cn);
dr = cm.ExecuteReader();
int numbercols = dr.FieldCount;
int row = 1;
while(dr.Read())
{
for(int i = 0 ; i < numbercols ; i ++)
{
xlsheet.ActiveSheet.Cells[row,i+1] = dr.GetValue(i).ToString();
}
row++;
}
dr.Close();
cn.Close();
cm.Dispose();
xlsheet.ActiveSheet.Export(Server.MapPath(".") + "\\" + this.file.Text,SheetExportActionEnum.ssExportActionNone);
}
Angelnet 2004-04-02
  • 打赏
  • 举报
回复
UP
sy246 2004-04-02
  • 打赏
  • 举报
回复
好爽!
gengwei80 2004-04-02
  • 打赏
  • 举报
回复
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OWC;

namespace cominterop
{
public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
private SqlCommand sql;
protected System.Web.UI.WebControls.Button export2excel;
protected System.Web.UI.WebControls.TextBox xlfile;
private SqlConnection cnn;

private void Page_Load(object sender, System.EventArgs e)
{
this.BindDataGrid();
}

private void BindDataGrid() {
cnn = new SqlConnection("Initial Catalog=Northwind;Data Source=localhost;uid=sa;pwd=");
sql = new SqlCommand("select * from products",cnn);
cnn.Open();
SqlDataReader reader = sql.ExecuteReader();
this.DataGrid1.DataSource = reader;
this.DataGrid1.DataBind();
reader.Close();
cnn.Close();
}

private void WriteDataGrid2Excel() {
SpreadsheetClass xlsheet = new SpreadsheetClass();
cnn.Open();
SqlDataReader reader = this.sql.ExecuteReader();
int numbercols = reader.FieldCount;
int row=1;
while (reader.Read()) {
for (int i=0;i<numbercols;i++)
{
xlsheet.ActiveSheet.Cells[row,i+1] = reader.GetValue(i).ToString();
}
row++;
}
reader.Close();
cnn.Close();
xlsheet.ActiveSheet.Export(Server.MapPath(".")+"\\"+this.xlfile.Text,OWC.SheetExportActionEnum.ssExportActionNone);
}

private void export2excel_Click(object sender, System.EventArgs e)
{
if (this.xlfile.Text.Trim()!="")
{
this.WriteDataGrid2Excel();
}
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}

private void InitializeComponent()
{
this.export2excel.Click += new System.EventHandler(this.export2excel_Click);
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion

}
}
afei78223 2004-04-02
  • 打赏
  • 举报
回复
up
tongcheng 2004-04-02
  • 打赏
  • 举报
回复
learn
xiaowangtian 2004-04-02
  • 打赏
  • 举报
回复
using System.IO;
string strSql="select * from piwsorg ";
System.Data.DataTable tb;
tb=(new clsSql()).gettblist(strSql);
grd.DataSource=tb;
grd.DataBind();
int iRow;
String filenew=Page.MapPath("ImportData/bbb.xls");
FileStream f = new FileStream(filenew, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter fw = new StreamWriter(f, System.Text.Encoding.GetEncoding("GB2312"));
String OutputString="";
int i;
int[] arrCol=new int[] {0,1,3,5};
foreach (int iCol in arrCol)
{
OutputString = OutputString +"\t"+ tb.Columns[iCol].Caption;
}
OutputString = OutputString.Trim();
fw.WriteLine(OutputString.Trim());
fw.WriteLine("");
for(iRow=0;iRow<=tb.Rows.Count-1;iRow++)
{
OutputString = "";
foreach (int iCol in arrCol)
{
OutputString = OutputString + "\t" + tb.Rows[iRow][iCol].ToString();
}
fw.WriteLine(OutputString.Trim());
}
fw.Close();
f.Close();

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧