关于c#生成word。
需求:
需要把数据做成这样的效果、一个页面展示一个r单子数据。
object filename = "";
Object Nothing = System.Reflection.Missing.Value;
Word.Application WordApp = new Word.ApplicationClass();//实例化word
HY.Common.Utils.Logger.Log.Info("WordApp:" + WordApp);
Word._Application oWord = new Word.Application();
//创建Word文档
Word._Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
try
{
SetPage(WordApp, WordDoc, "横板", , 29.7, , , , );
HY.Common.Utils.Logger.Log.Info("WordDoc:" + WordDoc);
string name = "审批表" + DateTime.Now.ToString("yyyyMMdd") + DateTime.Now.ToLongTimeString().Replace(":", "") + ".docx";//创建生成文件名字
HY.Common.Utils.Logger.Log.Info("name" + name);
string CreateFilePath = ConfigurationManager.AppSettings["CreateFilePath"];
HY.Common.Utils.Logger.Log.Info("CreateFilePath" + CreateFilePath);
filename = CreateFilePath + name; //文件保存路径
HY.Common.Utils.Logger.Log.Info("filename" + filename);
string[] SerialNumberArr = Context.Request["SerialNumber"].Substring(, Context.Request["SerialNumber"].ToString().Length - ).Split(','); string[] ProcInstIDArr = Context.Request["ProcInstID"].Substring(, Context.Request["ProcInstID"].ToString().Length - ).Split(',');//挂账Id
string[] PaymentProcInstIDArr = Context.Request["PaymentProcInstID"].Substring(, Context.Request["PaymentProcInstID"].ToString().Length - ).Split(',');//付款Id for (int i = ; i < ProcInstIDArr.Length; i++)
{
#region 打印 InsertText(WordDoc, " 审批表 ", new System.Drawing.Font("微软雅黑", , System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); InsertText(WordDoc, "", new System.Drawing.Font("微软雅黑", , System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, true);
InsertText(WordDoc, "申请人信息", new System.Drawing.Font("宋体", , System.Drawing.FontStyle.Bold), Word.WdParagraphAlignment.wdAlignParagraphLeft, false); if (ProcInstIDArr.Length - != i)
{
InsertBreak(WordDoc, Nothing);
}
#endregion
}
WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
WordApp = null; HY.Common.Utils.Logger.Log.Info("SaveAs" + filename); }
catch (Exception ex)
{ HY.Common.Utils.Logger.Log.Info("error" + e.ToString());
}
finally
{
WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
oWord.Quit(ref Nothing, ref Nothing, ref Nothing);
KillWordProcess();
}
#region - 插入文本 -
public static bool InsertText(Word._Document oDoc, string strText, System.Drawing.Font font, Word.WdParagraphAlignment wdAlign, bool isAftre)
{
try
{
Word.Range rng = oDoc.Content; int lenght = oDoc.Characters.Count - ;
object start = lenght;
object end = lenght; rng = oDoc.Range(ref start, ref end); if (isAftre == true)
{
strText += "\r\n";
} rng.Text = strText; rng.Font.Name = font.Name;
rng.Font.Size = font.Size;
if (font.Style == System.Drawing.FontStyle.Bold) { rng.Font.Bold = ; } //设置单元格中字体为粗体
rng.ParagraphFormat.Alignment = wdAlign;//设置文本对齐格式(左对齐,右对齐,居中)
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入分页符 -
public static void InsertBreak(Word._Document WordDoc, Object Nothing)
{
Word.Paragraph para;
para = WordDoc.Content.Paragraphs.Add(ref Nothing);
object pBreak = (int)Word.WdBreakType.wdSectionBreakNextPage;
para.Range.InsertBreak(ref pBreak);
}
public static void DeleteBreak(Word.Application wordApp, Object Nothing)
{
Word.Range range1, range2;
// 跳转种类
object objWhat = Word.WdGoToItem.wdGoToPage;
// 跳转位置
object objWhich = Word.WdGoToDirection.wdGoToLast;
// 转向最后一页
wordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing);
// Range取得
range1 = wordApp.Selection.Range;
range2 = wordApp.ActiveDocument.Range(ref Nothing, ref Nothing);
object start = range1.Start;
object end = range2.End;
// 删除最后一页
wordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing);
}
#endregion
#region - 页面设置 -
public static void SetPage(Word.Application oWord, Word._Document oDoc, string orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
Logger.Log.Info("Word.Name" + oWord.Name);
Logger.Log.Info("oDoc" + oDoc);
oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width);
oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height); if (orientation == "横板")
{
oDoc.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientLandscape;
}
oDoc.PageSetup.TopMargin = (float)(topMargin * );//上边距
oDoc.PageSetup.LeftMargin = (float)(leftMargin * );//左边距
oDoc.PageSetup.RightMargin = (float)(rightMargin * );//右边距
oDoc.PageSetup.BottomMargin = (float)(bottomMargin * );//下边距
}
#endregion
#region - 清除word进程 -
/**/
/// <summary>
/// 清除word进程
/// </summary>
public static void KillWordProcess()
{
System.Diagnostics.Process[] myPs;
myPs = System.Diagnostics.Process.GetProcesses();
foreach (System.Diagnostics.Process p in myPs)
{
if (p.Id != )
{
string myS = "WINWORD.EXE" + p.ProcessName + " ID:" + p.Id.ToString();
try
{
if (p.Modules != null)
if (p.Modules.Count > )
{
System.Diagnostics.ProcessModule pm = p.Modules[];
myS += "/n Modules[0].FileName:" + pm.FileName;
myS += "/n Modules[0].ModuleName:" + pm.ModuleName;
myS += "/n Modules[0].FileVersionInfo:/n" + pm.FileVersionInfo.ToString();
if (pm.ModuleName.ToLower() == "winword.exe")
p.Kill();
}
}
catch
{ }
finally
{ }
}
}
}
#endregion
遇到的问题:
1.由于需要每一个页面显示一个单子、所以每次根据ProcInstIDArr[] 循环创建完以后、调用InsertBreak()生成下一个空白页面、导致最后会出现一个空白页面、
当时想到的是怎么删除最后一个空白页、通过在网上查询,说通过以下代码可以删除、最后拿下来试验发现无法实现。
//Word.Range range1, range2;
//// 跳转种类
//object objWhat = Word.WdGoToItem.wdGoToPage;
//// 跳转位置
//object objWhich = Word.WdGoToDirection.wdGoToLast;
//// 转向最后一页
//WordApp.Selection.GoTo(ref objWhat, ref objWhich, ref Nothing, ref Nothing);
//// Range取得
//range1 = WordApp.Selection.Range;
//range2 = WordApp.ActiveDocument.Range(ref Nothing, ref Nothing);
//object start = range1.Start;
//object end = range2.End;
//// 删除最后一页
//WordApp.ActiveDocument.Range(ref start, ref end).Delete(ref Nothing, ref Nothing);
中午跟同事请教:理理思路。发现完全是我想复杂了、只想着怎么删除,没有想过不去生成。最后通过一个if判断轻松解决问题。
遇到问题不要想的太复杂。
2.还有一个关于winword.exe进程未杀死的问题、 这个是今天早上发现的,早上打开服务器,发现服务器上出现N个word文档。进程里还有不下30个winword.exe进 程、详情点击
关于c#生成word。的更多相关文章
- Aspose.Words简单生成word文档
Aspose.Words简单生成word文档 Aspose.Words.Document doc = new Aspose.Words.Document(); Aspose.Words.Documen ...
- php 生成word的三种方式
原文地址 http://www.jb51.net/article/97253.htm 最近工作遇到关于生成word的问题 现在总结一下生成word的三种方法. btw:好像只要是标题带PHP的貌似点击 ...
- 代码批量生成WORD的遇到的问题及解决
好久没搞工具了,最近因为处理大规模公文处理单文档,自己写了个批量处理WORD的程序:在调试过程中,主要遇到两个问题 第一个是WORD的模板 数据很多,但是WORD模板只需要一个,将数据替换WORD里标 ...
- ASP.NET生成WORD文档,服务器部署注意事项
网上转的,留查备用,我服务器装的office2007所以修改的是Microsoft Office word97 - 2003 文档这一个. ASP.NET生成WORD文档服务器部署注意事项 1.Asp ...
- [转载]Matlab生成Word报告
最近在进行一批来料的检验测试,一个个手动填写报告存图片太慢了,就有了种想要使用Matlab在分析完后数据可以自动生成PDF报告的想法,于是就去网上搜索了相关的资料,发现Matlab中文论坛上有xiez ...
- POI生成WORD文档
h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...
- poi生成word文件
一.简介 对于poi来说,poi可以完成对word.excel.ppt的处理.word目前有两种文件格式,一种是doc后缀.另一种是docx后缀的.2007之前的版本都是doc后缀的,这种格式poi使 ...
- 根据指定Word模板生成Word文件
最近业务需要批量打印准考证信息 1.根据Table数据进行循环替换,每次替换的时候只替换Word中第一个Table的数据, 2.每次替换之后将Word中第一个Table数据进行复制,将复制Table和 ...
- 使用freemarker生成word,步骤详解并奉上源代码
1. 步骤 1. 用word编辑好模板 1. 普通字符串替换为 ${string} 2. 表格循环用标签 <#list userList as user> 姓名:${user.u ...
- PHP生成word的三种方式
摘要: 最近工作遇到关于生成word的问题 现在总结一下生成word的三种方法. btw:好像在博客园发表博客只要是标题带PHP的貌似点击量都不是很高(哥哥我标题还是带上PHP了),不知道为什么,估计 ...
随机推荐
- MapReduce之Partition的使用与分析
Partition主要作用就是将map的结果发送到相应的reduce.这就对partition有两个要求: 1)均衡负载,尽量的将工作均匀的分配给不同的reduce. 2)效率,分配速度一定要快. M ...
- Android实例-路径信息及文件和文件夹的操作(XE8+小米2)
结果: GetTempFileName:/storage/sdcard0/Android/data/com.embarcadero.Project1/files/tmp/tmp.iQIip24407 ...
- (原创)vagrant up 异常报错,出现 There was an error while executing `VBoxManage` 的解决方法
最近在使用 vagrant homestead 时,不小心在虚拟机上使用了 exit 命令退出虚拟机,导致再使用 vagrant up 时出现以下错误: Bringing machine 'larav ...
- ISE和Modelsim联合仿真(转)
相信很多人会遇到过这个问题,不知如何让ISE调用Modelsim进行仿真.我也迷糊了不少时间,查查找找,终于弄明白了,所以有了本文,和大家分享一下.我尽量讲得详细点儿,多多上图. 我的环境:Windo ...
- session 重写进入redis测试
在实际业务中,当session存储过多 或者操作频繁,业务逐渐扩展的时候,文件存储已经无法满足session操作速度和需求,可以考虑用数据库或者nosql的redis来存储session,本文讲解如何 ...
- 【STL源码学习】STL算法学习之二
第一章:前言 学习笔记,记录学习STL算法的一些个人所得,在以后想用的时候可以快速拾起. 第二章:明细 copy 函数原型: template <class InputIterator, cla ...
- Redis实战之Redis + Jedis
用Memcached,对于缓存对象大小有要求,单个对象不得大于1MB,且不支持复杂的数据类型,譬如SET 等.基于这些限制,有必要考虑Redis! 相关链接: Redis实战 Redis实战之Redi ...
- 使用CATransition实现页面的“从左向右” “从右向左”的动画
-(void)initView{ UISwipeGestureRecognizer *left_gesture=[[UISwipeGestureRecognizer alloc]initWithTar ...
- COM编程VS实践
目录 1. 2. 2.1. 2.2. 2.3. 3. 3.1. 3.2. 3.3. 1.COM实践简介 因需要对Office系列进行程序操作,特研究了一下COM相关的编程. 个人体会:COM面向接口编 ...
- [RxJS] ReplaySubject
A ReplaySubject caches its values and re-emits them to any Observer that subscrubes late to it. Unli ...