亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

使用C#實(shí)現(xiàn)將Word?轉(zhuǎn)文本存儲(chǔ)到數(shù)據(jù)庫并進(jìn)行管理

 更新時(shí)間:2024年03月25日 08:40:32   作者:初九之潛龍勿用  
這篇文章主要為大家詳細(xì)介紹了如何使用C#實(shí)現(xiàn)將Word?轉(zhuǎn)文本存儲(chǔ)到數(shù)據(jù)庫并進(jìn)行管理,文中的示例代碼講解詳細(xì),需要的小伙伴可以參考一下

功能需求

將 WORD 文件的二進(jìn)制信息存儲(chǔ)到數(shù)據(jù)庫里,即方便了統(tǒng)一管理文件,又可以實(shí)行權(quán)限控制效果,此外,將 WORD 文件轉(zhuǎn)化為文本存儲(chǔ),可以進(jìn)一步實(shí)現(xiàn)對(duì)已存儲(chǔ)文件的全文檢索。 在應(yīng)用項(xiàng)目里,我們將實(shí)現(xiàn)如下需求:

1、上傳WORD文件,獲取二進(jìn)制數(shù)據(jù)和文本數(shù)據(jù)。

2、將二進(jìn)制數(shù)據(jù)和文本數(shù)據(jù)保存到數(shù)據(jù)表中。

3、查詢需要的數(shù)據(jù)文件,可提供下載功能。

范例運(yùn)行環(huán)境

操作系統(tǒng): Windows Server 2019 DataCenter

操作系統(tǒng)上安裝 Office Word 2016

數(shù)據(jù)庫:Microsoft SQL Server 2016

.net版本: .netFramework4.7.1 或以上

開發(fā)工具:VS2019  C#

設(shè)計(jì)數(shù)據(jù)表

打開 Microsoft SQL Server 2016 查詢分析器,執(zhí)行如下代碼創(chuàng)建表:

代碼片斷如下: 

CREATE TABLE [dbo].[f_words](
    [cid] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [filename] [nvarchar](100) NOT NULL,
    [bfile] [image] NULL,
    [fcontent] [nvarchar](max) NULL,
    [sys_instime] [datetime] NULL,
 CONSTRAINT [PK_f_words] PRIMARY KEY CLUSTERED 
(
    [cid] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
 
ALTER TABLE [dbo].[f_words] ADD  CONSTRAINT [DF_f_words_cid]  DEFAULT (newid()) FOR [cid]
GO

創(chuàng)建成功后,右擊f_words表,點(diǎn)擊設(shè)計(jì),呈現(xiàn)視圖如下:

如圖字段CID為唯一標(biāo)識(shí);filename存儲(chǔ)上傳時(shí)獲取的文件名;bfile存儲(chǔ)Word文件的二進(jìn)制數(shù)據(jù);fcontent存儲(chǔ)WORD文件的文本轉(zhuǎn)化信息;sys_instime存儲(chǔ)添加的時(shí)間。 

關(guān)鍵代碼

組件庫引入

Word文件內(nèi)容轉(zhuǎn)文本

public string getWordTxt(string _filename,bool getHtmlContent) 方法,參數(shù)1 傳入要讀取的 WORD 文件路徑,參數(shù)2 設(shè)定是否獲取HTML格式的文本。

public string getWordTxt(string _filename,bool getHtmlContent)
        {
            resultReport = "";
            Object Nothing = System.Reflection.Missing.Value;
 
            object filename = _filename;
            //創(chuàng)建一個(gè)名為WordApp的組件對(duì)象
            DateTime beforetime = DateTime.Now;
            Word.Application WordApp = new Word.Application();
            //創(chuàng)建一個(gè)名為WordDoc的文檔對(duì)象
            WordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
 
            Word.Document WordDoc = WordApp.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
 
            WordDoc.SpellingChecked = false;//關(guān)閉拼寫檢查
 
            WordDoc.ShowSpellingErrors = false;//關(guān)閉顯示拼寫錯(cuò)誤提示框
 
            DateTime aftertime = DateTime.Now;
 
            string rv = WordDoc.Content.Text;
            Sys_Custom_DocVar = "";
            Sys_Custom_DocVar2 = "";
            foreach (Word.Variable ov in WordDoc.Variables)
            {
                if (ov.Name == "sys_custom_docvar")
                {
                    //                    WordDoc.Content.Text = ov.Value;
                    Sys_Custom_DocVar = ov.Value;
                } else if (ov.Name == "sys_custom_docvar2")
                {
                    //                    WordDoc.Content.Text = ov.Value;
                    Sys_Custom_DocVar2 = ov.Value;
                }
            }
            foreach (Word.ContentControl cc in WordDoc.ContentControls)
            {
                resultReport += cc.ID + ":" + cc.Tag + "<br>";
 
            }
            string _path = Path.GetDirectoryName(_filename) + "\\";
 
            object _expFile = _path + Guid.NewGuid().ToString() + ".html";
            if (getHtmlContent == true)
            {
                object   wsf = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
                WordDoc.SaveAs2(ref _expFile,ref wsf, ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing,ref Nothing);
            }
            WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
            //關(guān)閉WordApp組件對(duì)象
            WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
 
            KillProcessByStartTime("WINWORD",beforetime,aftertime);
 
            if (File.Exists(_expFile.ToString()) == true)
            {
                FileEx fe = new FileEx();
                rv = fe.LoadFromFile(_expFile.ToString(), Encoding.Default);
                File.Delete(_expFile.ToString());
            }
            return rv;
        }
 
public string KillProcessByStartTime(string processName,DateTime beforetime,DateTime aftertime)
        {
            Process[] ps = Process.GetProcesses();
            foreach (Process p in ps)  
            {
                if(p.ProcessName.ToUpper()!=processName) continue;
                if(p.StartTime > beforetime && p.StartTime < aftertime)
                {
                    try
                    {
                        p.Kill();
                    }
                    catch(Exception e)
                    {
                        return e.Message;
                    }
                }
            }  
            return "";
        }

上傳及保存舉例

本示例是獲取上傳的文件并保存,將保存后的文件獲取二進(jìn)制及文本數(shù)據(jù)存儲(chǔ)到數(shù)據(jù)庫中。

示例代碼如下:

string filename = Request.PhysicalApplicationPath + "\\app_data\\" + Guid.NewGuid().ToString() + ".docx";  //預(yù)生成文件名
//File1為上傳控件
File1.PostedFile.SaveAs(filename);  //保存文件
 
//添加SQL參數(shù),此處僅為示例
ArrayList paras = new ArrayList();
paras.Add(new SqlParameter("filename", filename));
paras.Add(new SqlParameter("fcontent", getWordTxt(filename,false)));  //word轉(zhuǎn)文本
paras.Add(new SqlParameter("bfile", GetBinaryData(filename)));  //word的二進(jìn)制信息
paras.Add(new SqlParameter("sys_instime", System.DateTime.Now));
 
File.Delete(filename);
 
//保存到數(shù)據(jù)表
ExecDbScripts("INSERT INTO [f_words]([filename],[bfile],[fcontent],[sys_instime])  VALUES(@filename, @bfile,@fcontent,@sys_instime)", paras);
得到文件Byte[]數(shù)據(jù)方法
public byte[] GetBinaryData(string filename)
{
    if(!File.Exists(filename))
    {
        return null;
    }
    FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
    byte[] imageData = new Byte[fs.Length];
    fs.Read( imageData, 0,Convert.ToInt32(fs.Length));
    fs.Close();
    return imageData;
}        

查詢并下載Word文件

我們可以通過 select filename from f_words where fcontent like '%key%' 等語句形式進(jìn)行查詢結(jié)果,對(duì)于結(jié)果中的數(shù)據(jù)我們可以通過傳遞CID唯一標(biāo)識(shí)參數(shù),定位二進(jìn)制信息進(jìn)行下載,示例代碼如下:

 
  string strConn =ConfigurationSettings.AppSettings["Connection"];
  SqlConnection Conn = new SqlConnection(strConn );
  SqlCommand Cmd = new SqlCommand();
 
  Cmd.Connection = Conn;
 
  SqlDataReader myDr;
 
  Cmd.CommandText = " select filename from f_words where  cid=@cid ";
   
 
  SqlParameter   para2=new   SqlParameter("@cid",SqlDbType.UniqueIdentifier);
  para2.Value=(new Guid(_cid));
  Cmd.Parameters.Add(para2);
  try
  {
             Conn.Open();
             myDr = Cmd.ExecuteReader();
             bool _hasrows=myDr.HasRows;
             if (myDr.Read())
             {
 
                 string extendname = "docx";
 
                 byte[] bytes = (byte[])myDr["bfile"];
                 
                 
                 Response.Buffer = true;
                 Response.Charset = "utf-8";
                 Response.AppendHeader("Content-Disposition", "inline;filename=" + HttpUtility.UrlEncode(myDr["filename"].ToString() + "" + extendname)); //把 attachment 改為 online 則在線打開
                 Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                 Response.AppendHeader("Content-Length", bytes.Length.ToString());
                 Response.ContentType = "application/octet-stream"; 
                 
                     Page.EnableViewState = false;
                     Response.BinaryWrite(bytes);
                     Response.Flush();
             }
             myDr.Close();
         }
         catch (SqlException ex)
         {
         }
         finally
         {
             Conn.Close();
             Conn.Dispose();
         }
}

總結(jié)

上傳保存到數(shù)據(jù)庫的代碼僅供參考,添加參數(shù)僅為抽象調(diào)用,需要自行實(shí)現(xiàn)數(shù)據(jù)操作代碼。

下載大尺寸文件使用 Response.BinaryWrite() 方法可能會(huì)使瀏覽器無響應(yīng),可考慮使用 bytes.Length  判斷如果尺寸較大的話,則生成文件到服務(wù)器并提供URL下載鏈接的方法。

以上就是使用C#實(shí)現(xiàn)將Word 轉(zhuǎn)文本存儲(chǔ)到數(shù)據(jù)庫并進(jìn)行管理的詳細(xì)內(nèi)容,更多關(guān)于C# Word 轉(zhuǎn)文本的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論