如何使用纯ASP创建真正的二进制Excel文件



是否可以在ASP Classic中创建二进制Excel文件?

常用方法是使用这个

Response.ContentType = "application/octet-stream"
Response.AddHeader "Content-Disposition", "attachment; filename=test.txt"

这不是一个"真正的"Excel文件

在.net中,您可以使用Microsoft.Office.Interop.Excel命名空间 - 非常易于使用,如果您可以访问.net,我肯定会这样做。

你说"纯 asp"——如果这意味着没有 com 对象等——我认为这是不可能的。

但是,如果您希望坚持使用经典的asp,可以选择使用com对象,则可以使用Interop com对象创建完整的二进制电子表格 - 为此,您需要在Web服务器上安装Excel。

例如,要在磁盘上打开一个空白的 excel 文件(即模板),请更改一个值并保存完成的文件:

'#### Ready Excel
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Application.Visible = True
'#### Open a blank Excel File
Set ExcelBook = ExcelApp.workbooks.Open("d:wwwroot2blankTemplate.xls")
'#### Select a sheet and change the value of a cell
ExcelBook.Worksheets("SheetName").Cells(1, 1).Value = "Lorem Ipsum"
'#### Switch between sheets
ExcelBook.Worksheets("AnotherSheetName").Select
'#### Save the finished file with a different name (to leave the template ready for easy re-use)
ExcelBook.SaveAs "d:wwwroot2FinishedFile.xls"
'#### Tidy up
ExcelBook.Close
ExcelApp.Application.Quit
Set ExcelApp = Nothing 
Set ExcelBook = Nothing

这种方法的好处是互操作 com 对象非常接近地模仿 VBA 方法等,因此,如果您不确定如何执行某些操作,请在 excel 中记录宏,查看原始 vba,它生成的代码,特别是方法和参数在大多数情况下与您用于 com 对象的代码非常相似。

最新更新