关于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了),不知道为什么,估计 ...
随机推荐
- 《Genesis-3D开源游戏引擎完整实例教程-跑酷游戏篇01:道路的自动生成》
1.道路的自动生成 道路自动生成概述: 3D跑酷游戏的核心就是跑,在跑这一过程中增加趣味性使得游戏具有更多的可玩性.道路的自动生成和自由拼接,为游戏增设了更多的不可预见性.这种不可预见性使得玩家在游戏 ...
- PetShop学习第四天
ASP.NET缓存 1.页输出缓存分为整页缓存和部分页缓存.我们可以通过@OutputCache指令来完成对Web页面的输出缓存.
- INTERIGHT 京东自营旗舰店-京东 要把凡客给弄残啊这是。。
INTERIGHT 京东自营旗舰店-京东
- 软件开发中的单一职责(转至INFOQ)
最近在实践微服务化过程中,对其“单一职责”原则深有体会.那么只有微服务化才可以单一职责,才可以解耦吗?答案是否定的. 单一职责原则是这样定义的:单一的功能,并且完全封装起来. 我们做后端Java开发的 ...
- Altium Designer快捷键 【worldsing笔记】
Shift + R 切换三种布线模式 (忽略, 避开或推挤) Shift + E 触发电气格点开/关 Shift + B 建立查询 Shift + PgUp 放大到最小的递增 Shift + PgDn ...
- [置顶] MapReduce 编程之 倒排索引
本文调试环境: ubuntu 10.04 , hadoop-1.0.2 hadoop装的是伪分布模式,就是只有一个节点,集namenode, datanode, jobtracker, tasktra ...
- Java的面向对象思想
多态性: 一种方法有多种实现,采用哪一种实现由Java虚拟机在运行时动态决定,这种能力成为动态绑定(dynamic binding),也称为多态性(polymorphism)(源于一个希腊单词,意为“ ...
- 有如下Student 对象, private String name; private int age; private int score; private String classNum; 其中,classNum
package homework003; import java.util.ArrayList; import java.util.List; public class Text { public s ...
- eclipse 护眼色
eclipse windows 窗口背景颜色 保护视力 博客分类: 工具使用 EclipseWindows eclipse 窗口背景颜色 windows 窗口背景颜色
- UITableViewcell autolayout下动态高度
项目中最经常使用的一个UI就是UITableView了.iOS7.8进一步优化了复用机制,用起来相当爽.配合Autolayout,适配工作减轻了非常多. 曾经做适配工作都是在heightForRow里 ...