Answers
把数据集DataTable 导到Excel里
别人写的:
using OWC;
using System.Data.OleDb;
using System.IO;
SpreadsheetClass xlsheet=new SpreadsheetClass();
conn.Open();
cmd=new OleDbCommand(sql,conn);
OleDbDataReader reader=cmd.ExecuteReader();
int numbercols=reader.FieldCount;
int row=2;
int i=0;
//输出标题
for(i=0;i <numbercols;i++)
{
xlsheet.ActiveSheet.Cells[1, i + 1] = reader.GetName(i).ToString();
}
// 输出字段内容
while(reader.Read())
{
for(i=0;i <numbercols;i++)
{
xlsheet.ActiveSheet.Cells[row, i + 1] = reader.GetValue(i).ToString();
}
row = row + 1;
}
reader.Close();
conn.Close();
try
{
xlsheet.ActiveSheet.Export(Server.MapPath( ". ") + "\mfExcel\ " + this.xlfile.Text+ ".xls ",OWC.SheetExportActionEnum.ssExportActionNone);
}
catch(System.Runtime.InteropServices.COMException e )
{
Response.Write( "错误: " + e.Message);
}
private void btnMIME_Click(object sender, System.EventArgs e)
{
BindData();
Response.ContentType = "application/vnd.ms-excel ";
Response.AddHeader( "Content-Disposition ", "inline;filename= "
+ HttpUtility.UrlEncode( "下载文件.xls ",Encoding.UTF8 ) );
//如果输出为Word,修改为以下代码
//Response.ContentType = "application/ms-word "
//Response.AddHeader( "Content-Disposition ", "inline;filename=test.doc ")
StringBuilder sb=new StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
sb.Append( " <html> <body> ");
dgShow.RenderControl(hw);
sb.Append( " </body> </html> ");
Response.Write(sb.ToString());
Response.End();
}
如果有分页,目前知道的方法只有去掉分页,用RenderControl方法导出为Excel