使用C#實現(xiàn)將Word?轉(zhuǎn)文本存儲到數(shù)據(jù)庫并進行管理
功能需求
將 WORD 文件的二進制信息存儲到數(shù)據(jù)庫里,即方便了統(tǒng)一管理文件,又可以實行權(quán)限控制效果,此外,將 WORD 文件轉(zhuǎn)化為文本存儲,可以進一步實現(xiàn)對已存儲文件的全文檢索。 在應(yīng)用項目里,我們將實現(xiàn)如下需求:
1、上傳WORD文件,獲取二進制數(shù)據(jù)和文本數(shù)據(jù)。
2、將二進制數(shù)據(jù)和文本數(shù)據(jù)保存到數(shù)據(jù)表中。
3、查詢需要的數(shù)據(jù)文件,可提供下載功能。
范例運行環(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è)計數(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表,點擊設(shè)計,呈現(xiàn)視圖如下:

如圖字段CID為唯一標識;filename存儲上傳時獲取的文件名;bfile存儲Word文件的二進制數(shù)據(jù);fcontent存儲WORD文件的文本轉(zhuǎn)化信息;sys_instime存儲添加的時間。
關(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)建一個名為WordApp的組件對象
DateTime beforetime = DateTime.Now;
Word.Application WordApp = new Word.Application();
//創(chuàng)建一個名為WordDoc的文檔對象
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)閉顯示拼寫錯誤提示框
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組件對象
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 "";
}上傳及保存舉例
本示例是獲取上傳的文件并保存,將保存后的文件獲取二進制及文本數(shù)據(jù)存儲到數(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的二進制信息
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%' 等語句形式進行查詢結(jié)果,對于結(jié)果中的數(shù)據(jù)我們可以通過傳遞CID唯一標識參數(shù),定位二進制信息進行下載,示例代碼如下:
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)用,需要自行實現(xiàn)數(shù)據(jù)操作代碼。
下載大尺寸文件使用 Response.BinaryWrite() 方法可能會使瀏覽器無響應(yīng),可考慮使用 bytes.Length 判斷如果尺寸較大的話,則生成文件到服務(wù)器并提供URL下載鏈接的方法。
以上就是使用C#實現(xiàn)將Word 轉(zhuǎn)文本存儲到數(shù)據(jù)庫并進行管理的詳細內(nèi)容,更多關(guān)于C# Word 轉(zhuǎn)文本的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法
這篇文章主要介紹了DevExpress實現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法,需要的朋友可以參考下2014-08-08
c# socket心跳超時檢測的思路(適用于超大量TCP連接情況下)
這篇文章主要介紹了c# socket心跳超時檢測的思路(適用于超大量TCP連接情況下),幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03

