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

要实现从数据库中读取数据并将数据拼接成字符串,从而写入流,但生成的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就正常不出乱码了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值