2011-12-16 70 views
7

我正在用c#和sql server做一個程序,我有一個問題,我希望有人幫助我。從數據庫打開word文檔(保存爲二進制文件)

我會把PC上的數據庫和程序安裝在其他PC上,並將app的程序連接到該數據庫。

程序保存文檔(word -excel)爲二進制,使用此代碼:

byte[] ReadFile(string sPath) 
    { 
     //Initialize byte array with a null value initially. 
     byte[] data = null; 

     //Use FileInfo object to get file size. 
     FileInfo fInfo = new FileInfo(sPath); 
     long numBytes = fInfo.Length; 

     //Open FileStream to read file 
     FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read); 

     //Use BinaryReader to read file stream into byte array. 
     BinaryReader br = new BinaryReader(fStream); 

     //When you use BinaryReader, you need to supply number of bytes to read from file. 
     //In this case we want to read entire file. So supplying total number of bytes. 
     data = br.ReadBytes((int)numBytes); 
     return data; 
    } 

private void button1_Click(object sender, EventArgs e) 
    { 
     string dt = dateTimePicker1.Value.ToShortDateString(); 

     byte[] red = ReadFile(textBox3.Text); 
     con.Open(); 
     string qry = "insert into documents ([Account no],Name,[Phone number],Date,[Document name],Document,Type) values(@accon,@name,@phone,@date,@docname,@doc,@type)"; 

     //Initialize SqlCommand object for insert. 
     SqlCommand SqlCom = new SqlCommand(qry, con); 

     //We are passing Original Image Path and Image byte data as sql parameters. 

     SqlCom.Parameters.Add(new SqlParameter("@accon", textBox1.Text)); 
     SqlCom.Parameters.Add(new SqlParameter("@name", textBox2.Text)); 
     SqlCom.Parameters.Add(new SqlParameter("@phone", textBox3.Text)); 
     SqlCom.Parameters.Add(new SqlParameter("@date", dt)); 
     SqlCom.Parameters.Add(new SqlParameter("@docname", textBox1.Text)); 
     SqlCom.Parameters.Add(new SqlParameter("@doc", (object)red)); 

     SqlCom.Parameters.Add(new SqlParameter("@type", (object)textBox2.Text)); 
     SqlCom.ExecuteNonQuery(); 
     con.Close(); 

     MessageBox.Show("done"); 
    } 

的問題:我不知道如何在數據庫中檢索保存的文檔,並與Microsoft Word或打開根據他們的類型的Microsoft Excel。

我想選擇特定的文檔格式的數據庫,並提前打開

感謝

+0

你在「Type」for Word中存儲什麼,在Excel中存儲什麼? – 2011-12-16 09:22:33

回答

11
String connStr = "connection string"; 

// add here extension that depends on your file type 
string fileName = Path.GetTempFileName() + ".doc"; 

using (SqlConnection conn = new SqlConnection(connStr)) 
{ 
    conn.Open(); 
    using (SqlCommand cmd = conn.CreateCommand()) 
    { 
     // you have to distinguish here which document, I assume that there is an `id` column 
     cmd.CommandText = "select document from documents where id = @id"; 
     cmd.Parameters.Add("@id", SqlDbType.Int).Value = 1; 
     using (SqlDataReader dr = cmd.ExecuteReader()) 
     { 
      while (dr.Read()) 
      { 
       int size = 1024 * 1024; 
       byte[] buffer = new byte[size]; 
       int readBytes = 0; 
       int index = 0; 

       using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) 
       { 
        while ((readBytes = (int)dr.GetBytes(0, index, buffer, 0, size)) > 0) 
        { 
         fs.Write(buffer, 0, readBytes); 
         index += readBytes; 
        } 
       } 
      } 
     } 
    } 
} 

// open your file, the proper application will be executed because of proper file extension 
Process prc = new Process(); 
prc.StartInfo.FileName = fileName; 
prc.Start(); 
0

的癥結是Response.ContentType

Response.ContentType = "application/vnd.xls"; // for excel 
Response.ContentType = "application/ms-word"; // for word 
Response.ContentType = "image/jpg";//for jpg images 

這是應還存儲內容類型在數據庫中,以便您的代碼將是通用的,並且可以顯示/存儲任何類型的文件

System.Data.SqlClient.SqlDataReader rdr = null; 
System.Data.SqlClient.SqlConnection conn = null; 
System.Data.SqlClient.SqlCommand selcmd = null; 
try 
{ 
    conn = new System.Data.SqlClient.SqlConnection(
     System.Configuration.ConfigurationManager 
     .ConnectionStrings["ConnectionString"].ConnectionString); 
    selcmd = new System.Data.SqlClient.SqlCommand(
     "select pic1 from msg where msgid=" + Request.QueryString["imgid"], 
     conn); 

    conn.Open(); 
    rdr = selcmd.ExecuteReader(); 
    while (rdr.Read()) 
    { 
     Response.ContentType = "image/jpg"; 
     Response.BinaryWrite((byte[])rdr["pic1"]); 
    } 
    if (rdr != null) 
     rdr.Close(); 
} 
finally 
{ 
    if (conn != null) 
     conn.Close(); 
} 
+0

謝謝你,這是非常有用的建議 我嘗試這個代碼,並顯示此錯誤 錯誤名稱「請求」不會在目前情況下\t 存在的,我加的System.Web參考,並用它 – moonshine 2011-12-16 11:03:41

+0

OI是這樣抱歉!你問了關於Windows應用程序,我已經給出了Web應用程序的解決方案。 – Zia 2011-12-16 12:10:45

+0

不要提到它, 謝謝你的幫助:) – moonshine 2011-12-16 17:35:22

0

從數據庫(或您在服務器上使用的任何類型的存儲)中檢索文檔後,應將文檔保存在Windows臨時文件夾(Path.GetSpecialFolder)中,並使用Word Interop庫啓動word(或使用自己的互操作庫excel)與您剛剛保存的文檔。

var temporayFileName = Path.GetRandomFileName(); 
var temporaryFileStream = File.Open(temporaryFileName, FileMode.Create); 
var memoryStream = documentRepository.Get(...); 
memoryStream.CopyTo(temporaryFileStream); 

// Word App 
dynamic wordApp = new Application { Visible = true }; 
var doc = wordApp.Documents.Add(TemplateName); 
templatedDocument.Activate(); 

(見本文件有關啓動和操縱字的詳細信息: http://msdn.microsoft.com/en-us/magazine/ff714583.aspx) 。