1.ActiveX组件的引用:
2.实现示例代码:
3.相关问题:
a.new Excel.Application()会报出“拒绝访问”?
1.ActiveX组件的引用:
Microsoft Excel 11.0 Object Library
2.实现示例代码:
'输出文件名
Dim printBookName As String = ""
'类声明
Dim excelApp As Excel.Application
'文件名
Dim excelBook As Excel.Workbook
'页
Dim excelSheet As Excel.Worksheet
'EXCEL模板名
Dim strTemplateBookName As String
'页名
Dim sheetName As String
'数据开始行
Dim nStartRowNo As Integer = 7
'模板文件夹路径
strTemplateBookName = "C:/Inetpub/wwwroot/Test/template/template.xls"
'输出文件名
printBookName = "C:/Inetpub/wwwroot/Test/download/"
printBookName += "data_" + Date.Now().ToString("yyyyMMddHHmmss") + ".xls"
'页名
sheetName = "Data1"
'数据处理
Try
'模板文件复制
FileCopy(strTemplateBookName, printBookName)
System.IO.File.SetAttributes(printBookName, IO.FileAttributes.Normal)
'声明
excelApp = New Excel.Application
'文件打开
excelBook = excelApp.Workbooks.Open(printBookName)
'页的选择
excelSheet = excelBook.Sheets(sheetName)
'标题的设定
excelSheet.Range("A1").Value = Me.lblPageTitle.Text
'数据的设定(其中tblData的定义是:Protected WithEvents tblData As System.Web.UI.WebControls.Table)
For cnt As Integer = 1 To tblData.Rows.Count - 1
'CHECKBOX列的设置
If CType(Page.FindControl("chk1" + (cnt - 1).ToString()), CheckBox).Checked = True Then
excelSheet.Range("A" + (nStartRowNo + cnt).ToString()).Value = "有"
ElseIf CType(Page.FindControl("chk1" + (cnt - 1).ToString()), CheckBox).Checked = False Then
excelSheet.Range("A" + (nStartRowNo + cnt).ToString()).Value = "无"
End If
'给CELL加边框
excelSheet.Range("A" + (nStartRowNo + cnt).ToString()).Borders.LineStyle = Excel.XlLineStyle.xlContinuous
'内容2(将tblData的值赋给CELL)
excelSheet.Range("B" + (nStartRowNo + cnt).ToString()).Value = tblData.Rows.Item(cnt).Cells.Item(2).Text.ToString()
excelSheet.Range("B" + (nStartRowNo + cnt).ToString()).Borders.LineStyle = Excel.XlLineStyle.xlContinuous
Next
Catch ex As Exception
Finally
If Not excelBook Is Nothing Then
' 对象释放处理
excelBook.Save()
excelBook.Close()
End If
' 对象释放处理
If Not excelApp Is Nothing Then
excelApp.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)
excelSheet = Nothing
excelBook = Nothing
excelApp = Nothing
GC.Collect()
End If
End Try
3.相关问题:
a.new Excel.Application()会报出“拒绝访问”?
方法1:
"开始"---》"运行"---》输入"dcomcnfg"---》应用程序---》Microsoft Excel应用程序---》属性---》安全性---》您可以编辑能启动该应用程序的用户---》添加账号ASPNET。
方法2:
在web.config
<configuration>
<system.web>中加入
<identity impersonate="true"/>
本文介绍如何利用ActiveX组件操作Excel文件,包括复制模板、填充数据、设置样式等步骤,并解决权限问题。
474

被折叠的 条评论
为什么被折叠?



