c# word操作篇,解决字符串长度超过255就不能替换的问题
本文使用的是Microsoft.Office.Interop.Word组件,必须在系统安装了office相关组件的条件下进行,在com里面找到Microsoft Word 16.0 Object Library并引用。
问题:使用c#操作word替换占位符的时候,当要替换的字符串超过一定的长度,就会提示“字符串参量过长”,搜索发现,替换的最大长度为255字符。
以220个字符串为例,执行替换工作。
//构造数据
Dictionary<string, string> datas = new Dictionary<string, string>() { { "{name}", "张三" }, { "{sex}", "男" }, { "{provinve}", "浙江" } };
//模板文件
object path = Server.MapPath("/Template/template.docx");
//生成文件
string physicNewFile = Server.MapPath("/createdfile/" + Guid.NewGuid().ToString() + ".docx");
/// <summary>
/// 根据模板生成替换文件并下载
/// </summary>
/// <param name="path">文件/模板地址</param>
/// <param name="datas">需要替换的key:value集合</param>
/// <param name="physicNewFile">生成文件地址</param>
public void ReplaceToWord(object path, Dictionary<string, string> datas, string physicNewFile)
{
Microsoft.Office.Interop.Word.Application app = null;
Microsoft.Office.Interop.Word._Document doc = null;
object oMissing = System.Reflection.Missing.Value;
try
{
app = new Microsoft.Office.Interop.Word.Application();
object fileName = path;
//打开模板文件
doc = app.Documents.Open(ref fileName,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; foreach (var item in datas)
{
app.Selection.Find.Replacement.ClearFormatting();
app.Selection.Find.ClearFormatting();
if (item.Value.Length > 220)
FindAndReplaceLong(app, item.Key, item.Value);
else
FindAndReplace(app, item.Key, item.Value);
} //对替换好的word模板另存为一个新的word文档
doc.SaveAs(physicNewFile,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
oMissing, oMissing, oMissing, oMissing, oMissing, oMissing); //准备导出word
Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".doc");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.ContentType = "application/ms-word";
Response.End();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (doc != null)
{
//关闭word文档
doc.Close(ref oMissing, ref oMissing, ref oMissing);
doc = null;
}
if (app != null)
{
//退出word应用程序
app.Quit(ref oMissing, ref oMissing, ref oMissing);
app = null;
}
//GC.Collect();
//GC.WaitForPendingFinalizers();
//GC.Collect();
//GC.WaitForPendingFinalizers();
//如果文件存在则输出到客户端
if (System.IO.File.Exists(physicNewFile))
{
Response.WriteFile(physicNewFile);
}
}
}
/// <summary>
/// 根据字符串长度执行替换操作
/// </summary>
/// <param name="wordApp">当前word程序</param>
/// <param name="findText">占位符(key)</param>
/// <param name="replaceText">替换字符串(值)</param>
public void FindAndReplaceLong(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
{
int len = replaceText.ToString().Length; //要替换的文字长度
int cnt = len / 220; //不超过220个字
string newstr;
object newStrs;
if (len < 220) //小于220字直接替换
{
FindAndReplace(wordApp, findText, replaceText);
}
else
{
for (int i = 0; i <= cnt; i++)
{
if (i != cnt)
newstr = replaceText.ToString().Substring(i * 220, 220) + findText; //新的替换字符串
else
newstr = replaceText.ToString().Substring(i * 220, len - i * 220); //最后一段需要替换的文字
newStrs = newstr;
FindAndReplace(wordApp, findText, newStrs); //进行替换
}
}
}
/// <summary>
/// 执行替换操作
/// </summary>
/// <param name="wordApp">当前word程序</param>
/// <param name="findText">占位符(key)</param>
/// <param name="replaceText">替换字符串(值)</param>
public void FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceText)
{
//object oMissing = System.Reflection.Missing.Value;
object matchCase = true;
object matchWholeWord = true;
object matchWildCards = false;
object matchSoundsLike = false;
object matchAllWordForms = false;
object forward = true;
object format = false;
object matchKashida = false;
object matchDiacritics = false;
object matchAlefHamza = false;
object matchControl = false;
object read_only = false;
object visible = true;
object replace = 2; //object replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
object wrap = 1;
wordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceText,
ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza, ref matchControl);
// wordApp.Selection.Find.Execute( ref oMissing, ref oMissing,ref oMissing, ref oMissing,ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,ref oMissing, ref replace,
//ref oMissing, ref oMissing,ref oMissing, ref oMissing);
}
Asp.Net操作Word内容
如果要正常操作Word Com组件的话,必须要给用户赋上足够的权限的,
1、运行Dcomcnfg.exe
2、组件服务――计算机――我的电脑――DCOM配置――找到microsoft word 文档
3、点击属性
4、选择“安全性”
5、选定“使用自定义访问权限”和“使用自定义启动权限”
6、分别编辑权限,添加ASPNET,VS Developers,Debugger User //不一定
7、选择“身份标识”,在选定“交互式用户” 即可 (关键步骤)必须
8、在Web.config里加 <identity impersonate="true"/>
参考链接:http://www.cnblogs.com/riddly/p/9231719.html
c# word操作篇,解决字符串长度超过255就不能替换的问题的更多相关文章
- EXCEL某列长度超过255个字符导入SQL SERVER的处理方法
问题描述: [Excel 源 [1]] 错误: 输出“Excel 源输出”(9) 上的 输出列“Description 3”(546) 出错.返回的列状态是:“文本被截断,或者一个或多个字符在目标代码 ...
- C#中用OLEDB操作EXCEL时,单元格内容长度超过255被截断
C#中Microsoft.ACE.OLEDB.12.0 驱动读取excel,会读取前8行来判定每列的数据类型,假如没有超过255个字符,那么会被设置为nvarchar(255),从第9行开始,超过25 ...
- 用OLEDB读取EXCEL时,单元格内容长度超过255被截断
https://support.microsoft.com/zh-cn/help/189897/data-truncated-to-255-characters-with-excel-odbc-dri ...
- EXCEL某列长度超过255个字符导入SQL SERVER2005的处理方法
将注册表中 Jet引擎. HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Jet/4.0/Engines/Excel 如果是:ACE引擎. HKEY_LOCAL_MACHI ...
- angularjs如何在ng-repeat过程中控制字符串长度超过指定长度后面内容以省略号显示
angular.module('ng').filter('cut', function () { return function (value, wordwise, max, tail) { if ( ...
- C#导出Excel,某单元格内容长度超过255 的解决方法
public static void ToExcel(DataTable dtSource, string strPath, string strSheetName) { System.Data.Ol ...
- ora 32021 设置参数时参数值长度超过255处理办法
alter system set db_file_name_convert='AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA-.' scope=spfi ...
- .NET MVC JSON JavaScriptSerializer 字符串的长度超过 maxJsonLength 值问题的解决
[ArgumentException: 使用 JSON JavaScriptSerializer 序列化或还原序列化期间发生错误.字符串的长度超过在 maxJsonLength 属性上设定的值. 参数 ...
- ASP.NET MVC Json()处理大数据异常解决方法,字符串的长度超过了为 maxJsonLength
问题: 使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错.字符串的长度超过了为 maxJsonLength 属性设置的值. <system.web.exten ...
随机推荐
- 记一下JavaScript的几种排序算法
零.写在最前 排序的方法有很多种,这篇文章只是记录我熟悉的算法: 我发现了一个关于排序算法很有趣的网站,把相关的算法演示做成了动画,有兴趣的同学可以看看! 附上SortAnimate网站链接:http ...
- <airsim文档学习> Street View Image, Pose, and 3D Cities Dataset
原文地址: https://github.com/amir32002/3D_Street_View 说明:个人学习笔记,翻译整理自github/airsim. 简介 该存储库共享包含6DOF相机姿态 ...
- Saiku登录源码追踪.(十三)
Saiku登录源码追踪呀~ >>首先我们需要debug跟踪saiku登录执行的源码信息 saiku源码的debug方式上一篇博客已有说明,这里简单介绍一下 在saiku启动脚本中添加如下命 ...
- SQL-61 对于employees表中,给出奇数行的first_name
题目描述 对于employees表中,给出奇数行的first_nameCREATE TABLE `employees` (`emp_no` int(11) NOT NULL,`birth_date` ...
- 【webdriver自动化】Python数据驱动工具DDT
一.Python数据驱动工具ddt 1. 安装 ddt pip install ddt DDT是 “Data-Driven Tests”的缩写 资料:http://ddt.readthedocs.i ...
- Windows系统,Tensorflow的Tensorboard工具细节问题
随着跟着TensorFlow视频学习,学到Tensorboard可视化工具这里的时候. 在windows,cmd里面运行,tensorboard --logdir=你logs文件夹地址 这行代码,一 ...
- js基础概念-操作符
操作符是操作数据值的符号,也叫做运算符. 按照操作个数分为:一元运算符,二元运算符,三元运算符. 按功能分为:位操作符,布尔操作符,乘性操作符,加性操作符,关系操作符,关系操作符,相等操作符,条件操作 ...
- python print()内置函数
啦啦啦啦啦啦,我又来了,学习任何东西都得坚持,我一定的好好加油!!! 今天来说说print()函数,前边我们已经用过好好多次啦,现在来学习哈吧!!! Python的内置函数,print() print ...
- Ubuntu16.04交叉工具链安装
前言: 开发环境是64位的ubuntu16.04,交叉工具链是通过sudo apt-get install ....安装的,移植uboot2014.10,但是很奇怪,按照网上的介绍在start.s里面 ...
- eclipse中,将springboot项目打成jar包
1.右击项目,选择Run As - Maven clean 2.右击项目,选择Run As - Maven install 3.成功后 会在项目的target文件夹下生成jar包 4.将打包好的jar ...