SSIS调用SSRS报表:如何正确将Excel输出保存为.xlsx而非.xls
解决SSRS导出Excel文件损坏的问题
问题根源
你遇到的文件损坏,是因为SSRS默认的&rs:Format=EXCEL参数导出的是旧版BIFF格式(对应.xls),强行改扩展名.xlsx会导致格式不匹配,Excel无法正常识别。你看到的""51""是SSRS导出标准Open XML格式(.xlsx)的格式代码。
解决方案
需要调整两个核心部分:指定正确的导出格式参数,确保保存的文件名格式匹配。
修改后的完整代码
Imports System Imports System.Data Imports System.Math Imports Microsoft.SqlServer.Dts.Runtime Imports System.ComponentModel Imports System.Diagnostics <Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute()> <System.CLSCompliantAttribute(False)> Partial Public Class ScriptMain Inherits Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase Enum ScriptResults Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure End Enum Protected Sub SaveFile(ByVal url As String, ByVal localpath As String) Dim loRequest As System.Net.HttpWebRequest Dim loResponse As System.Net.HttpWebResponse Dim loResponseStream As System.IO.Stream Dim loFileStream As New System.IO.FileStream(localpath, System.IO.FileMode.Create, System.IO.FileAccess.Write) Dim laBytes(256) As Byte Dim liCount As Integer = 1 Try loRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest) loRequest.Credentials = System.Net.CredentialCache.DefaultCredentials loRequest.Timeout = 600000 loRequest.Method = "GET" loResponse = CType(loRequest.GetResponse, System.Net.HttpWebResponse) loResponseStream = loResponse.GetResponseStream Do While liCount > 0 liCount = loResponseStream.Read(laBytes, 0, 256) loFileStream.Write(laBytes, 0, liCount) Loop loFileStream.Flush() loFileStream.Close() Catch ex As Exception ' 新增异常日志,方便排查问题 Dts.Events.FireError(0, "SaveFile Error", ex.Message & vbCrLf & ex.StackTrace, String.Empty, 0) Dts.TaskResult = ScriptResults.Failure End Try End Sub Public Sub Main() Dim url, destination As String ' 保持文件名后缀为.xlsx destination = Dts.Variables("Folder_Destination").Value.ToString & "\" & Dts.Variables("ReportName").Value.ToString & Dts.Variables("OutPutDate").Value.ToString & ".xlsx" ' 替换格式参数为EXCELOPENXML(或用&rs:Format=51,两者等价) url = Dts.Variables("ReportURL").Value.ToString & Dts.Variables("Location").Value.ToString & "&DateType=" & Dts.Variables("DateType").Value.ToString & Dts.Variables("ServiceArea").Value.ToString & "&StartDate=" & Dts.Variables("START_DATE").Value.ToString & "&EndDate=" & Dts.Variables("END_DATE").Value.ToString & "&rs:Format=EXCELOPENXML" SaveFile(url, destination) Dts.TaskResult = ScriptResults.Success End Sub End Class
关键修改说明
- 格式参数调整:把
&rs:Format=EXCEL替换为&rs:Format=EXCELOPENXML(或者直接用&rs:Format=51,51是该格式对应的数字代码,效果完全一致),让SSRS导出标准的.xlsx格式文件。 - 字符串拼接优化:将原代码中的
+替换为&,VB.NET中用&做字符串拼接能避免潜在的类型转换错误。 - 异常处理增强:在Catch块中添加了错误日志触发,避免原代码吞掉异常导致无法排查问题。
额外注意事项
- 确保SSRS服务器版本为SQL Server 2008 R2及以上,该版本才支持EXCELOPENXML格式导出。
- 检查
Folder_Destination变量的路径末尾是否带有反斜杠,避免拼接后出现无效路径。
内容的提问来源于stack exchange,提问作者gfuller40
相关产品推荐
相关产品推荐

