word文檔和二進制數據的轉換及相關問題探討
2024-08-22 13:39:54
供稿:網友
現在很多項目和技術支持在線編輯word文檔。有控件的和javascript操作的。這里簡單的推薦一個在線編輯word文檔的控件。
地址:http://www.dianju.cn/p/weboffice/
在這個控件中,word文檔的編輯很好用。但是這里面用到兩個方法。word文檔和數據庫保存的二進制之間的轉換問題。
現在將word文檔和二進制數據之間相互轉換的兩個方法總結如下
復制代碼代碼如下:
/// <summary>
/// 將二進制數據轉換為word文檔
/// </summary>
/// <param name="data">二進制數據可以直接存放在sql server數據庫中的數據</param>
/// <param name="fileName">文件名,即你要生成的word文檔的名稱。自己隨便定義一個字符串就行</param>
public void ByteConvertWord(byte[] data, string fileName)
{
string savePath = @"/Upload/"; //虛擬路徑,項目中的虛擬路徑。一般我們條用這個方法,肯定要把生成的word文檔保存在項目的一個文件夾下,以備后續使用
string path = Server.MapPath(savePath); //把相應的虛擬路徑轉換成物理路徑
if (!System.IO.Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
savePath += fileName + DateTime.Now.ToString().Replace("-", "").Replace(" ", "").Replace(":", "") + Guid.NewGuid().ToString() + ".doc";
string filePath = Server.MapPath(savePath);
FileStream fs;
if (System.IO.File.Exists(filePath))
{
fs = new FileStream(filePath, FileMode.Truncate);
}
else
{
fs = new FileStream(filePath, FileMode.CreateNew);
}
BinaryWriter br = new BinaryWriter(fs);
br.Write(data, 0, data.Length);
br.Close();
fs.Close();
}
以下介紹word文檔轉換為二進制數據的方法。
復制代碼代碼如下:
/// <summary>
/// word文件轉換二進制數據(用于保存數據庫)
/// </summary>
/// <param name="wordPath">word文件路徑</param>
/// <returns>二進制</returns>
private byte[] wordConvertByte(string wordPath)
{
byte[] bytContent = null;
System.IO.FileStream fs = null;
System.IO.BinaryReader br = null;
try
{
fs = new FileStream(wordPath, System.IO.FileMode.Open);
}
catch
{
}
br = new BinaryReader((Stream)fs);
bytContent = br.ReadBytes((Int32)fs.Length);
return bytContent;
}