2011-02-11 66 views
1

我已经在我的SQL Server 2008数据库中存储了一个excel文件(作为VARBINARY(MAX))以下(到目前为止,硬编码)的方式:如何通过C#在SQL Server 2008中打开一个存储的Excel文件

// C# - visual studio 2008 
var update = new SqlCommand("UPDATE Requests SET Attachment = @xls" + 
     " WHERE RequestsID = 27", conn); 
    update.Parameters.AddWithValue("xls", File.ReadAllBytes("C:/aFolder/hello.xlsx")); 
    update.ExecuteNonQuery(); 

它的工作,但我也想打开它
我该怎么做? 请注意,不是读取blob-data,而是打开实际的“hello.xlsx”文件。

我曾尝试以下: http://dotnetsoldier.blogspot.com/2007/07/how-to-retrieve-blob-object-in-winforms.html 我可以看到它的工作原理,如“Binary.Length”是在执行时,我的“hello.xlsx”的确切规模 - 但doesn't打开该文件,并that'是我的问题。

请帮我一把!

编辑: 这里是代码,我目前使用的“打开”电子表格:

SqlConnection conn = 
     new SqlConnection 
      (global::MY_PROJECT.Properties.Settings.Default.DB_1ConnectionString); 

    conn.Open(); 

    SqlCommand Cmd = new SqlCommand("select Attachment from Requests where RequestsID = 27", conn); 
    Cmd.CommandType = CommandType.Text; 

    SqlDataReader Reader = Cmd.ExecuteReader(CommandBehavior.CloseConnection); 
    // 
    string DocumentName = null; 
    FileStream FStream = null; 
    BinaryWriter BWriter = null; 
    // 
    // 
    // 
    byte[] Binary = null; 
    const int ChunkSize = 100; 
    int SizeToWrite = 0; 
    MemoryStream MStream = null; 
    // 
    while (Reader.Read()) 
    { 
     DocumentName = Reader["Attachment"].ToString(); 
     // Create a file to hold the output. 
     FStream = new FileStream(@"c:\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write); 
     BWriter = new BinaryWriter(FStream); 
     Binary = (Reader["Attachment"]) as byte[]; 
     SizeToWrite = ChunkSize; 
     MStream = new MemoryStream(Binary); 
     // 
     for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize) 
     { 
      if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i; 
      byte[] Chunk = new byte[SizeToWrite]; 
      MStream.Read(Chunk, 0, SizeToWrite); 
      BWriter.Write(Chunk); 
      BWriter.Flush(); 
     } 
     BWriter.Close(); 
     FStream.Close(); 
    } 
    FStream.Dispose(); 

    conn.Close(); 
+0

请发布您用于打开电子表格的代码。 – Lazarus 2011-02-11 11:56:30

+0

好的 - 完成了! – 2011-02-11 12:29:53

回答

1

您发布看起来类似的代码,它可能写入电子表格到光盘,但我看不到任何代码打开它。您需要使用类似

System.Diagnostics.Process.Start(@"c:\" + DocumentName) 

我想。