2011-12-16 39 views
7

Tôi đang tạo một chương trình với máy chủ C# và sql và tôi gặp sự cố, tôi hy vọng nếu có ai giúp tôi.tài liệu mở từ (được lưu dưới dạng nhị phân) từ cơ sở dữ liệu

Tôi sẽ nhưng cơ sở dữ liệu trên máy tính và chương trình sẽ được cài đặt trong các máy tính khác và chương trình ứng dụng được kết nối với cơ sở dữ liệu đó.

các tài liệu tiết kiệm chương trình (word -excel) như nhị phân, sử dụng mã này:

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"); 
    } 

vấn đề: mà tôi không biết làm thế nào để lấy tài liệu được lưu trong cơ sở dữ liệu và mở nó với Microsoft từ hoặc Microsoft Excel theo loại của họ.

Tôi muốn chọn cơ sở dữ liệu dạng văn bản cụ thể và mở nó

Cảm ơn trước

+0

Bạn lưu trữ gì trong 'Loại' cho Word và điều gì cho Excel? –

Trả lời

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

Thực sự tôi không biết cảm ơn bạn, tôi đã dành rất nhiều thời gian trong vấn đề này và tôi không tìm thấy giải pháp phù hợp. Cảm ơn rất nhiều :)))) – moonshine

+0

@moonshine, không cần phải cảm ơn. Chỉ cần chấp nhận (và bỏ phiếu nếu bạn thực sự thích) câu trả lời là như nhau :-). –

+1

Tôi chấp nhận nhưng bỏ phiếu cần 15 danh tiếng, tôi chỉ có 11 danh tiếng khi tôi đạt đến 15 tôi sẽ bỏ phiếu cho bạn chắc chắn :) – moonshine

0

Điểm mấu chốt là Response.ContentType:

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

Nó được khuyên nên lưu trữ kiểu nội dung cũng trong cơ sở dữ liệu để mã của bạn sẽ chung chung và có thể hiển thị/lưu trữ bất kỳ loại tệp nào

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

cảm ơn bạn, đó là lời khuyên hữu ích Tôi đã thử mã này và hiển thị lỗi này Lỗi Tên 'Yêu cầu' không tồn tại trong bối cảnh hiện nay \t và tôi đã thêm System.Web tham khảo và sử dụng nó – moonshine

+0

oi đang rất lấy làm tiếc ! bạn đã hỏi về ứng dụng cửa sổ và tôi đã đưa ra giải pháp cho ứng dụng web. – Zia

+0

Đừng đề cập đến nó, cảm ơn bạn đã giúp bạn :) – moonshine

0

Sau khi bạn đã truy xuất tài liệu của bạn từ cơ sở dữ liệu (hoặc bất kỳ loại lưu trữ nào bạn sử dụng trên máy chủ), bạn nên lưu tài liệu trong thư mục tạm thời của cửa sổ (Path.GetSpecialFolder) và sử dụng thư viện Word Interop để bắt đầu từ (hoặc excel sử dụng thư viện interop riêng của nó) với tài liệu bạn vừa lưu.

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

(Xem tài liệu này để biết thêm thông tin về việc bắt đầu và thao tác từ: http://msdn.microsoft.com/en-us/magazine/ff714583.aspx) .

+0

cảm ơn bạn, nhưng tôi đã không lưu tài liệu trong máy chủ Tôi đã lưu nó dưới dạng nhị phân trong cơ sở dữ liệu – moonshine

+0

Việc mã tài liệu của bạn trở nên không quan trọng tài liệu của nó. Hoặc là câu hỏi của bạn làm thế nào để lấy dữ liệu nhị phân? – Jaapjan

+0

vâng, cảm ơn rất nhiều sự giúp đỡ của bạn – moonshine

Các vấn đề liên quan