从数据库中打开word文档(保存为二进制文件)

时间:2011-12-16 08:46:52

标签: c# sql-server ms-word

我正在使用c#和sql server编写程序,我遇到了问题,希望有人帮助我。

我会,但是pc上的数据库和程序将安装在其他PC上,并且app pcs的程序连接到该数据库。

程序将文档(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打开它。

我想选择特定的文档表单数据库并打开它

提前致谢

3 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分: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();
}

答案 2 :(得分:0)

从数据库(或您在服务器上使用的任何类型的存储)中检索文档后,应将文档保存在Windows临时文件夹(Path.GetSpecialFolder)中,并使用Word 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