从SQL Server Image字段导出的Word文档无法打开,求排查解决
问题:SQL Server Image字段导出Word文件无法读取
我使用SQL Server 2017数据库,某表的Image类型字段存储了Word doc文件。通过代码导出该字段内容生成doc文件时,文件生成无报错,但用Microsoft Word打开时提示文件不可读。
我的代码如下:
Sub Main(args As String()) Dim connectionString As String = GetConnectionString() Dim filePath As String = GetDirectoryRadiceLocale() + "\verbali\" + args(0) + ".doc" Dim WordContents As Byte() Dim selectStmt As String = "SELECT verbale FROM testata_assemblea WHERE id_assemblea = @id" Using connection As SqlConnection = New SqlConnection(connectionString) Using cmdSelect As SqlCommand = New SqlCommand(selectStmt, connection) cmdSelect.Parameters.Add("@ID", SqlDbType.Int).Value = CInt(args(0)) connection.Open() WordContents = CType(cmdSelect.ExecuteScalar(), Byte()) connection.Close() End Using End Using File.WriteAllBytes(filePath, WordContents) End Sub
已尝试的操作:
- 尝试多种方案均未解决;
- 使用SQL Image View工具可正常显示字段中的Word文件,但导出后的文件仍无法被Word读取(报错提示:文件不可读,可能是文件损坏、使用了不兼容的文件格式或文件权限问题)。
问题排查及解决建议:
1. 替换读取方式,避免大字段截断
ExecuteScalar()在处理较大的二进制字段时可能出现数据截断,建议改用SqlDataReader的GetBytes()方法完整读取数据,示例代码如下:
Sub Main(args As String()) Dim connectionString As String = GetConnectionString() Dim filePath As String = GetDirectoryRadiceLocale() + "\verbali\" + args(0) + ".doc" Dim selectStmt As String = "SELECT verbale FROM testata_assemblea WHERE id_assemblea = @id" Using connection As New SqlConnection(connectionString) Using cmdSelect As New SqlCommand(selectStmt, connection) cmdSelect.Parameters.Add("@ID", SqlDbType.Int).Value = CInt(args(0)) connection.Open() Using reader As SqlDataReader = cmdSelect.ExecuteReader() If reader.Read() Then If Not reader.IsDBNull(0) Then Dim bufferSize As Integer = 4096 Dim byteBuffer(bufferSize - 1) As Byte Dim bytesRead As Long = 0 Dim totalBytes As Long = reader.GetBytes(0, 0, Nothing, 0, 0) Dim wordContents(totalBytes - 1) As Byte While bytesRead < totalBytes Dim chunkSize As Integer = reader.GetBytes(0, bytesRead, byteBuffer, 0, bufferSize) Array.Copy(byteBuffer, 0, wordContents, bytesRead, chunkSize) bytesRead += chunkSize End While File.WriteAllBytes(filePath, wordContents) End If End If End Using connection.Close() End Using End Using End Sub
2. 验证文件格式一致性
- 将SQL Image View能正常显示的文件导出,用二进制编辑器查看头部标识(
.doc格式的头部应为D0 CF 11 E0); - 对比你代码导出的文件头部,确认是否一致,排除数据库中存储的文件本身格式错误或被篡改的可能。
3. 核对文件字节大小
检查数据库中verbale字段的实际长度(可通过SELECT DATALENGTH(verbale) FROM testata_assemblea WHERE id_assemblea = @id查询),与导出文件的字节大小对比,确保数据没有丢失。
内容的提问来源于stack exchange,提问作者Emanuele Giuliani
相关产品推荐
相关产品推荐

