C#使用流处理写入WORD文件出现乱码

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/yiyelanxin/article/details/82700574

要实现从数据库中读取数据并将数据拼接成字符串,从而写入流,但生成的word中却是乱码。

代码如下:

string upLoadPath = GetUpLoadPath(); //上传目录相对路径
string CNumber = "LBSC" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
string newFileName = CNumber + ".doc"; //随机生成新的文件名
string fullUpLoadPath = DotNet.FrameWork.Common.API.SerializeHelper.GetMapPath(upLoadPath); //上传目录的物理路径
string newFilePath = upLoadPath + newFileName; //上传后的路径
string ReportFileName = fullUpLoadPath + newFileName;//上传后完整路径
string html = lab360WebUI.OrderHelper.GenerateAgreement(oid, CNumber);//拼接的字符串
FileStream Fs = new FileStream(ReportFileName, FileMode.Create);
BinaryWriter binWrite = new BinaryWriter(Fs, System.Text.Encoding.GetEncoding("UTF-8"));
binWrite.Write(html);
binWrite.Close();
Fs.Close();

byte[] byteArray = System.Text.Encoding.Default.GetBytes(html);

类FileStream是以二进制形式将基元类型写入流,并支持用特定的编码写入字符串。

所以出现乱码的原因是:虽然是用字符串写入方式,但是编码并不可控,既然FileStream可以二进制形式将基元类型写入流,那就将字符串转换成type[]类型之后再写入流。代码如下:

string upLoadPath = GetUpLoadPath(); //上传目录相对路径
string CNumber = "LBSC" + DateTime.Now.ToString("yyyyMMddHHmmssfff");
string newFileName = CNumber + ".doc"; //随机生成新的文件名
string fullUpLoadPath = DotNet.FrameWork.Common.API.SerializeHelper.GetMapPath(upLoadPath); //上传目录的物理路径
string newFilePath = upLoadPath + newFileName; //上传后的路径
string ReportFileName = fullUpLoadPath + newFileName;//上传后完整路径
string html = lab360WebUI.OrderHelper.GenerateAgreement(oid, CNumber);////拼接的字符串
byte[] byteArray = System.Text.Encoding.Default.GetBytes(html);
FileStream Fs = new FileStream(ReportFileName, FileMode.Create);
BinaryWriter binWrite = new BinaryWriter(Fs, System.Text.Encoding.GetEncoding("UTF-8"));
binWrite.Write(byteArray);
binWrite.Close();
Fs.Close();

这样写入之后导出的word就正常不出乱码了。

猜你喜欢

转载自blog.csdn.net/yiyelanxin/article/details/82700574