使用C#實現(xiàn)將Word?轉文本存儲到數(shù)據(jù)庫并進行管理
功能需求
將 WORD 文件的二進制信息存儲到數(shù)據(jù)庫里,即方便了統(tǒng)一管理文件,又可以實行權限控制效果,此外,將 WORD 文件轉化為文本存儲,可以進一步實現(xiàn)對已存儲文件的全文檢索。 在應用項目里,我們將實現(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ù)據(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表,點擊設計,呈現(xiàn)視圖如下:

如圖字段CID為唯一標識;filename存儲上傳時獲取的文件名;bfile存儲Word文件的二進制數(shù)據(jù);fcontent存儲WORD文件的文本轉化信息;sys_instime存儲添加的時間。
關鍵代碼
組件庫引入

Word文件內(nèi)容轉文本
public string getWordTxt(string _filename,bool getHtmlContent) 方法,參數(shù)1 傳入要讀取的 WORD 文件路徑,參數(shù)2 設定是否獲取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;//關閉拼寫檢查
WordDoc.ShowSpellingErrors = false;//關閉顯示拼寫錯誤提示框
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);
//關閉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"; //預生成文件名
//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轉文本
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%' 等語句形式進行查詢結果,對于結果中的數(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();
}
}總結
上傳保存到數(shù)據(jù)庫的代碼僅供參考,添加參數(shù)僅為抽象調(diào)用,需要自行實現(xiàn)數(shù)據(jù)操作代碼。
下載大尺寸文件使用 Response.BinaryWrite() 方法可能會使瀏覽器無響應,可考慮使用 bytes.Length 判斷如果尺寸較大的話,則生成文件到服務器并提供URL下載鏈接的方法。
以上就是使用C#實現(xiàn)將Word 轉文本存儲到數(shù)據(jù)庫并進行管理的詳細內(nèi)容,更多關于C# Word 轉文本的資料請關注腳本之家其它相關文章!
相關文章
C#拆分字符串正則表達式Regex.Split和String.Split方法
這篇文章主要給大家介紹了關于C#拆分字符串正則表達式Regex.Split和String.Split方法的相關資料,在C#中,Regex.Split方法和string.Split方法都用于分割字符串,但它們有一些重要的區(qū)別,文中通過代碼詳細講解下,需要的朋友可以參考下2024-04-04
C# DataGridView綁定數(shù)據(jù)源的方法
這篇文章主要為大家詳細介紹了C# DataGridView綁定數(shù)據(jù)源的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09
C#四舍五入MidpointRounding.AwayFromZero解析
這篇文章主要介紹了C#四舍五入MidpointRounding.AwayFromZero,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

