关于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了),不知道为什么,估计 ...
随机推荐
- Error starting static Resources java.lang.IllegalArgumentException: Document base D:\Program Files\apache-tomcat-xxx\webapps\xxx does not exist or is not a readable directory
网上的答案大多数如下: 但并没有解决我的问题 经过我的观察: 在tomcat的server.xml有Lottery项目描述,但实际上,该项目已被我删除,不存在于webapps中了 该行Cont ...
- HDU-4604 Deque DP
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4604 因为deque最后的数列是单调不降的,因此,我们可以枚举数列中的某个中间数Ai,如果从中间数Ai ...
- Android Binder------ServiceManager启动分析
ServiceManager启动分析 简述: ServiceManager是一个全局的manager.调用了Jni函数,实现addServicew getService checkService ...
- POJ 3764 (异或+字典树)
早就听过用字典树求异或最大值,然而没做过.发现一碰到异或的题就GG,而且因为以前做过的一道类似的题(事实上并不类似)限制了思路,蠢啊= =. 题意:一棵带权的树,求任意两点间路径异或的最大值. 题解: ...
- vs之Nuget
1.http://msdn.microsoft.com/zh-cn/magazine/hh547106.aspx 2.在Nuget控制台中安装特定版本: Install-Package <程序包 ...
- (原创)vagrant up 异常报错,出现 There was an error while executing `VBoxManage` 的解决方法
最近在使用 vagrant homestead 时,不小心在虚拟机上使用了 exit 命令退出虚拟机,导致再使用 vagrant up 时出现以下错误: Bringing machine 'larav ...
- AdapterView及其子类之二:使用ListActivity及ArrayAdapter创建列表
见归档项目ListActivityDemo.zip. 基本步骤如下: 1.创建一个TextView,用于指定每一个ListView的格式 <?xml version="1.0" ...
- 学习 MFC之 工具栏(二)
对于InitToolBar()函数进行进一步解析: 1.首先声明一个全局对象: CToolBar m_toolbar; 2.然后用create()创建toolbar: //创建ToolBar工具条 ...
- Android从入门到精通pdf+书源代码
不须要积分,免费放送 Android从入门到精通的pdf,入门的好书籍,因为csdn文件大小的限制所以分成了两部分. part1地址:http://download.csdn.net/detail/a ...
- C#-datagridview右键选中行
在datagridview中有时需要在右键点击某行的时候就选中它,那么我们只需要在datagridview的CellMonseDown事件中添加如下代码就行: && e.ColumnI ...