2011-12-16 5 views
7

私はC#とSQLサーバでプログラムを作っていますが、問題があります。オープンワード文書(バイナリとして保存)

私はPC上のデータベースではなく、プログラムは他のPCにインストールされ、アプリケーションPCのプログラムはそのデータベースに接続されます。私は、データベースに保存されたドキュメントを取得し、マイクロソフト・ワードでそれを開く方法がわからないということか:

プログラム、バイナリとして文書(ワード-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 Excelの種類に応じて。私は特定の文書形式のデータベースを選択し、事前に

感謝を開きたい

+0

Wordの場合は「タイプ」に、Excelの場合は何に保存しますか? –

答えて

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(); 
+2

本当にありがとう、私はこの問題で多くの時間を費やし、私は適切な解決策を見つけることができませんでした。 ありがとう:) :))) – moonshine

+0

@ムーンシャイン、ありがとうございます。あなたが本当に好きなら投票してください。それは同じです:-)。 –

+1

私は受け入れられましたが、投票が15の評判を必要とする、私は11名の評判しか持っていません 私が15に達すると確かに投票します:) – moonshine

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

+0

大井午前を使用して表示しごめんなさい !あなたはWindowsアプリについて尋ねた、私はWebアプリの解決策を与えていた。 – Zia

+0

ありがとうございました。 – moonshine

0

データベース(またはサーバー上で使用するのに気になるタイプのストレージ)からドキュメントを取得した後、Windowsの一時フォルダ(Path.GetSpecialFolder)にドキュメントを保存し、Word Interopライブラリを使用して単語を開始する必要があります独自のinteropライブラリを使用して)保存したドキュメントを使用して優れています。 :

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単語を開始し、操作の詳細については、このドキュメントを参照してください)。

+0

ありがとうございますが、サーバーに文書を保存しませんでした データベースにバイナリとして保存しました – moonshine

+0

documentRepositoryの取得方法はこのコードとは関係ありませんその文書。バイナリデータを取得する方法は? – Jaapjan

+0

はい、ありがとう、あなたの助けをたくさん – moonshine

関連する問題