How do I OPEN a stored excel file in SQL Server 2008 via C#
I have stored an excel file in my SQL Server 2008 DB (as a VARBINARY(MAX)) the following (so far, hard coded) way:
// 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();
It works, but I want to open it too!
How do I do that? Note, not read blob-data, but open the actual "hello.xlsx" file.I have tried the following: http://dotnetsoldier.blogspot.com/2007/07/how-to-retrieve-blob-object-in-winforms.html I can see it works, as "Binary.Length" is exactly the size of my "hello.xlsx" when executing - but the file doesn´t open, and that´s my problem.
Please help me out!
EDIT: HERE IS THE CODE THAT I CURRENTLY USE TO "OPEN" THE SPREADSHEET:
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();
The code you posted looks like it probably writes the spreadsheet to disc but I can't see any code to open it. You would need to use something like
System.Diagnostics.Process.Start(@"c:\" + DocumentName)
I think.
精彩评论