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));
} // itemresp.}();}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;
}
}}
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));
} // itemresp.}();}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;
}
}}
http://expert.csdn.net/Expert/topic/1645/1645967.xml
是.NET中的DataGrid
* 将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();
}
你的意思是WinForm下的,把你找到的代码用我给你网页下个转化软件就行了
{
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;
}
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();
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 }
}
{
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);
}
你的方法,如果DataGrid里面有汉字,Excel里面会有乱码