这样做的好处可以节省服务器与网络资源,不足在于安全问题,只适用于受信任的站点中。代码如下:
<script language="vbscript">
Function exportTableToExcel(tableID)
On Error Resume Next
alert ("如果出现提示:" & vbCrLf & vbCrLf & _
"在此页上的ActiveX控件和本页上的其它部分的交互可能不安全。你想允许这种交互吗?" & _
vbCrLf & vbCrLf & " 请点击[是]按钮!")
Dim excel
Dim mySheet
Dim objTable
Set excel = CreateObject("excel.application")
Set objTable = document.getElementById(tableID)
excel.Visible = True
excel.Workbooks.Add
Set mySheet = excel.Workbooks(1).Worksheets(1)
Dim objRows, objCellsInOneRow
Dim intR, intC
Dim records
intR = 1
intC = 1
records = objTable.Rows.Length
For Each objRows In objTable.Rows
intC = 1
mySheet.Cells(intR, 1).Select
For Each objCellsInOneRow In objRows.Cells
mySheet.Cells(intR, intC) = objCellsInOneRow.innerText
intC = intC + 1
Next
excel.StatusBar = "当前进度提示: " & Int(intR / records * 100) & "%"
intR = intR + 1
Next
mySheet.Cells.Select
mySheet.Cells.EntireColumn.AutoFit
mySheet.Cells(1, 1).Select
excel.StatusBar = "就绪"
alert ("数据已经全部导出!")
End Function
</script>
- 简单换一换样式
Function exportTableToExcel(tableID)
alert ("如果出现提示:" & vbCrLf & vbCrLf & _
"在此页上的ActiveX控件和本页上的其它部分的交互可能不安全。你想允许这种交互吗?" & _
vbCrLf & vbCrLf & " 请点击[是]按钮!")
Dim FSO, csvFile
Dim objTable
Dim intR, intC
Dim lineString
Set FSO = CreateObject("Scripting.FileSystemObject")
Set csvFile = FSO.CreateTextFile("c:/book1.csv", True)
Set objTable = Document.getElementById(tableID)
For intR = 0 To objTable.Rows.Length - 1
lineString = ""
For intC = 0 To objTable.Rows(intR).cells.Length - 1
lineString = lineString & Chr(34) & objTable.Rows(intR).cells(intC).innerText & Chr(34) & ","
Next
lineString = Left(lineString, Len(lineString) - 1)
csvFile.WriteLine (lineString)
Next
csvFile.Close
alert ("数据已经全部导出!")
End Function
补充一种服务器端处理的代码:
protected void exportToExcel_Click(object sender, EventArgs e)
{
string strDisplay = "姓名,年龄/n张三,18/n李四,45";
Response.ClearHeaders();
//下面这句没有的话中文会乱码,因为网页的默认编码是U-8
Response.ContentEncoding = Encoding.GetEncoding("GB2312");
Response.AppendHeader("Content-disposition", "inline;filename=ExportData.csv");
Response.AddHeader("Content-Type", "application/vnd.ms-excel;charset=gb2312");
Response.Write(strDisplay);
Response.End();
}