需求:需要把数据做成这样的效果、一个页面展示一个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。的更多相关文章

  1. Aspose.Words简单生成word文档

    Aspose.Words简单生成word文档 Aspose.Words.Document doc = new Aspose.Words.Document(); Aspose.Words.Documen ...

  2. php 生成word的三种方式

    原文地址 http://www.jb51.net/article/97253.htm 最近工作遇到关于生成word的问题 现在总结一下生成word的三种方法. btw:好像只要是标题带PHP的貌似点击 ...

  3. 代码批量生成WORD的遇到的问题及解决

    好久没搞工具了,最近因为处理大规模公文处理单文档,自己写了个批量处理WORD的程序:在调试过程中,主要遇到两个问题 第一个是WORD的模板 数据很多,但是WORD模板只需要一个,将数据替换WORD里标 ...

  4. ASP.NET生成WORD文档,服务器部署注意事项

    网上转的,留查备用,我服务器装的office2007所以修改的是Microsoft Office word97 - 2003 文档这一个. ASP.NET生成WORD文档服务器部署注意事项 1.Asp ...

  5. [转载]Matlab生成Word报告

    最近在进行一批来料的检验测试,一个个手动填写报告存图片太慢了,就有了种想要使用Matlab在分析完后数据可以自动生成PDF报告的想法,于是就去网上搜索了相关的资料,发现Matlab中文论坛上有xiez ...

  6. POI生成WORD文档

    h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h ...

  7. poi生成word文件

    一.简介 对于poi来说,poi可以完成对word.excel.ppt的处理.word目前有两种文件格式,一种是doc后缀.另一种是docx后缀的.2007之前的版本都是doc后缀的,这种格式poi使 ...

  8. 根据指定Word模板生成Word文件

    最近业务需要批量打印准考证信息 1.根据Table数据进行循环替换,每次替换的时候只替换Word中第一个Table的数据, 2.每次替换之后将Word中第一个Table数据进行复制,将复制Table和 ...

  9. 使用freemarker生成word,步骤详解并奉上源代码

    1.   步骤 1.    用word编辑好模板 1. 普通字符串替换为 ${string} 2. 表格循环用标签 <#list userList as user> 姓名:${user.u ...

  10. PHP生成word的三种方式

    摘要: 最近工作遇到关于生成word的问题 现在总结一下生成word的三种方法. btw:好像在博客园发表博客只要是标题带PHP的貌似点击量都不是很高(哥哥我标题还是带上PHP了),不知道为什么,估计 ...

随机推荐

  1. jquery 资料收集

    1.jquery 特效:http://www.yeshou-jquery.com/yeshou/jquery.html 2.jquery 无缝文字滚动效果(跑马灯效果)插件 Marquee(MSCla ...

  2. 【转载】高性能I/O设计模式Reactor和Proactor

    转载自:http://blog.csdn.net/roger_77/article/details/1555170 昨天购买了<程序员>杂志 2007.4期,第一时间去翻阅了一遍,其中有一 ...

  3. algorithm@ Strongly Connected Component

    Strongly Connected Components A directed graph is strongly connected if there is a path between all ...

  4. 图解Java字符串不变性

    1. 声明字符串 String s = "abcd"; 这里,s存储了“abcd”在这个字符串对象的引用,如下图所示: 2. 将字符串变量s赋值给字符串变量s2 String s2 ...

  5. 天天动听MP3解码器性能提升50%

    天天动听今日升级提醒,发现有一句 “使用新的MP3解码器,性能提升50%”,太惊讶了. 之前版本的MP3解码器使用libmpg123,效果已经是MP3解码器中非常不错的了. 50%的提升,应该不仅仅是 ...

  6. ANT打包J2EE项目war包

    1.下载并安装ant 2.安装ant步骤如下 .解压下载的zip包 .进入解压的目录,把bin目录放入系统变量PATH中. eg:E:\dev_tools\apache-ant-\bin .打开cmd ...

  7. Delphi- 操作EXCEL

    因工作需要,需要到操作EXCEL,先了解一下怎么读取EXCEL这个,做了一个DEMO,备注在这里 一.读取EXCEL unit Unit1; interface uses Windows, Messa ...

  8. C#公历转农历算法

    C#公历转农历算法,高手们也可以改写一下让其更加有效率! Code/// <summary> /// LunDay 的摘要说明. /// 用法说明 /// 直接调用即可,比较简单 /// ...

  9. hadoop安装与WordCount例子

    1.JDK安装 下载网址: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u29-download-513648.html  ...

  10. android驱动[置顶] 我的DIY Android之旅--驱动并控制你的Android开发板蜂鸣器

    改章节个人在深圳游玩的时候突然想到的...这几周就有想写几篇关于android驱动的博客,所以回家到之后就奋笔疾书的写出来发布了 这些天一直在想Android驱动框架层的实现,本文借助老罗教师的博客和 ...