word文档和二进制数据的转换及相关问题探讨

  发布时间:2013-01-31 14:50:31   作者:佚名   我要评论
现在很多项目和技术支持在线编辑word文档,接下来介绍将word文档和二进制数据之间相互转换的两个方法总结如下,感兴趣的朋友可以了解下啊,或许对你有所帮助
现在很多项目和技术支持在线编辑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;
}

相关文章

最新评论