众所周知,Respone.Write()是输出Html流程序给用户的。考虑到一个标准的Web页面的是有多种呈现方式的,
例如:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 这是以标准网页形式输出Html流
<meta http-equiv="Content-Type" content="application/vnd.ms-excel">
<meta http-equiv="Content-Disposition" content="attachment; filename=ex.xls">这是以附件形式输出Html流,而且是将“数据”存放在ex.xls这个表格中。^_^
那么我们以编码的形式如何显示^_^(现在写VB了,给出的也是VB的事例)
1 Dim _DataStringWriter As StringWriter = New StringWriter 定义一个StringWriter对象
2 _DataStringWriter.WiteLine("FirstFieldName" + ControlChars.Tab + "SecondFieldName")给输出的Excel表格每 列加入名称
3 从数据“容器”里面将数据取出。例如
Dim dt as New DataTable
For i as Integer = 0 To dt.Rows.Count - 1 Then
_DataStringWriter.WiteLine(dt(i)(0) + ControlChars.Tab + dt(i)(1))
Next
4 Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.ContentType = "application/vnd.ms-excel"
Response.ContentEncoding = System.Text.Encoding.Unicode
5 Response.Write(_DataStringWriter) 输出Html流
Response.End()
以上已经可以实现将数据导入到Excel表格,如果需要导入Word则Response.ContentType = "application/vnd.ms-excel"中改为Response.ContentType = "application/vnd.ms-word"即可。但是注意将fileName也应随之改变,XX.xls或者XX.doc
转载于:https://www.cnblogs.com/AndrewZhang/archive/2008/06/10/1216688.html