利用标签导出Word文档
1 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word; namespace QHRMS // 根据自己需要修改命名空间
{
public class CreateWordHelper
{
private _Application wordApp = null;
private _Document wordDoc = null;
public _Application Application
{
get
{
return wordApp;
}
set
{
wordApp = value;
}
}
public _Document Document
{
get
{
return wordDoc;
}
set
{
wordDoc = value;
}
} // 通过模板创建新文档
public bool CreateNewDocument(string filePath)
{
try
{ killWinWordProcess();
//wordApp=new Microsoft.Office.Interop.Word.Application();
wordApp = new ApplicationClass();
wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;
wordApp.Visible = false;
object missing = System.Reflection.Missing.Value;
object templateName = filePath;
wordDoc = wordApp.Documents.Open(ref templateName, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing);
return true;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return false;
}
} // 保存新文件
public void SaveDocument(string filePath)
{
object fileName = filePath;
object format = WdSaveFormat.wdFormatDocument;//保存格式
object miss = System.Reflection.Missing.Value;
wordDoc.SaveAs(ref fileName, ref format, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss, ref miss, ref miss, ref miss,
ref miss);
//关闭wordDoc,wordApp对象
object SaveChanges = WdSaveOptions.wdSaveChanges;
object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;
object RouteDocument = false;
wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument);
} // 在书签处插入值
public bool InsertValue(string bookmark, string value)
{
object bkObj = bookmark;
if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark))
{
wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();
wordApp.Selection.TypeText(value);
return true;
}
return false;
} // 插入表格,bookmark书签
public Table InsertTable(string bookmark, int rows, int columns, float width)
{
object miss = System.Reflection.Missing.Value;
object oStart = bookmark;
Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置
Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);
//设置表的格式
newTable.Borders.Enable = ; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)
newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度
if (width != )
{
newTable.PreferredWidth = width;//表格宽度
}
newTable.AllowPageBreaks = false;
return newTable;
} // 合并单元格 表id,开始行号,开始列号,结束行号,结束列号
public void MergeCell(int n, int row1, int column1, int row2, int column2)
{
wordDoc.Content.Tables[n].Cell(row1, column1).Merge(wordDoc.Content.Tables[n].Cell(row2, column2));
} // 合并单元格 表名,开始行号,开始列号,结束行号,结束列号
public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2)
{
table.Cell(row1, column1).Merge(table.Cell(row2, column2));
} // 设置表格内容对齐方式 Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)Microsoft.Office.Interop.Word.Table table
public void SetParagraph_Table(int n, int Align, int Vertical)
{
switch (Align)
{
case -: wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
case : wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
case : wordDoc.Content.Tables[n].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
}
switch (Vertical)
{
case -: wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
case : wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
case : wordDoc.Content.Tables[n].Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
}
} // 设置单元格内容对齐方式
public void SetParagraph_Table(int n, int row, int column, int Align, int Vertical)
{
switch (Align)
{
case -: wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐
case : wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中
case : wordDoc.Content.Tables[n].Cell(row, column).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
}
switch (Vertical)
{
case -: wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐
case : wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中
case : wordDoc.Content.Tables[n].Cell(row, column).Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
} } // 设置表格字体
public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size)
{
if (size != )
{
table.Range.Font.Size = Convert.ToSingle(size);
}
if (fontName != "")
{
table.Range.Font.Name = fontName;
}
} // 设置单元格字体
public void SetFont_Table(int n, int row, int column, string fontName, double size, int bold)
{
if (size != )
{
wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Size = Convert.ToSingle(size);
}
if (fontName != "")
{
wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Name = fontName;
}
wordDoc.Content.Tables[n].Cell(row, column).Range.Font.Bold = bold;// 0 表示不是粗体,其他值都是
} // 是否使用边框,n表格的序号,use是或否
// 该处边框参数可以用int代替bool可以让方法更全面
// 具体值方法中介绍
public void UseBorder(int n, bool use)
{
if (use)
{
wordDoc.Content.Tables[n].Borders.Enable = ;
//允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
}
else
{
wordDoc.Content.Tables[n].Borders.Enable = ;
}
} // 给表格插入一行,n表格的序号从1开始记
public void AddRow(int n)
{
object miss = System.Reflection.Missing.Value;
wordDoc.Content.Tables[n].Rows.Add(ref miss);
} // 给表格添加一行
public void AddRow(Microsoft.Office.Interop.Word.Table table)
{
object miss = System.Reflection.Missing.Value;
table.Rows.Add(ref miss);
} // 给表格插入rows行,n为表格的序号
public void AddRow(int n, int rows)
{
object miss = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
for (int i = ; i < rows; i++)
{
table.Rows.Add(ref miss);
}
} // 删除表格第rows行,n为表格的序号
public void DeleteRow(int n, int row)
{
Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
table.Rows[row].Delete();
} // 给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素
public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value)
{
table.Cell(row, column).Range.Text = value;
} // 给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素
public void InsertCell(int n, int row, int column, string value)
{
wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;
} // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
public void InsertCell(int n, int row, int columns, string[] values)
{
Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];
for (int i = ; i < columns; i++)
{
table.Cell(row, i + ).Range.Text = values[i];
}
} // 插入图片
public void InsertPicture(string bookmark, string picturePath, float width, float hight)
{
object miss = System.Reflection.Missing.Value;
object oStart = bookmark;
Object linkToFile = false; //图片是否为外部链接
Object saveWithDocument = true; //图片是否随文档一起保存
object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置
wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);
wordDoc.Application.ActiveDocument.InlineShapes[].Width = width; //设置图片宽度
wordDoc.Application.ActiveDocument.InlineShapes[].Height = hight; //设置图片高度
} // 插入一段文字,text为文字内容
public void InsertText(string bookmark, string text)
{
object oStart = bookmark;
object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;
Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);
wp.Format.SpaceBefore = ;
wp.Range.Text = text;
wp.Format.SpaceAfter = ;
wp.Range.InsertParagraphAfter();
wordDoc.Paragraphs.Last.Range.Text = "\n";
} // 杀掉winword.exe进程
public void killWinWordProcess()
{
System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");
foreach (System.Diagnostics.Process process in processes)
{
bool b = process.MainWindowTitle == "";
if (process.MainWindowTitle == "")
{
process.Kill();
}
}
}
}
}
简单的使用例子:
1、先建好Word文档,设置好排版、插入标签
2、代码如下:
private void button1_Click(object sender, EventArgs e)
{
Report report = new Report();
report.CreateNewDocument(Application.StartupPath + "\\WordDome.doc"); //模板路径
report.InsertValue("date1", "09月04日");//在书签处插入值
report.InsertValue("date2", "09月05日");
report.InsertValue("date3", "09月06日");
report.InsertValue("date4", "09月07日");
report.InsertValue("date5", "09月08日");
report.InsertValue("date6", "09月09日");
report.InsertValue("date7", "09月10日"); DataTable dtSource= GetTestDT(); int xx = dtSource.Rows.Count;
report.AddRow(, xx);
for (int i = ; i < xx; i++)
{
string[] values = { dtSource.Rows[i]["DEPT_NAME"].ToString(), dtSource.Rows[i]["C1"].ToString(), dtSource.Rows[i]["C2"].ToString(), dtSource.Rows[i]["C3"].ToString(),
dtSource.Rows[i]["C4"].ToString(),dtSource.Rows[i]["C5"].ToString(), dtSource.Rows[i]["C6"].ToString(), dtSource.Rows[i]["C7"].ToString()};
report.InsertCell(, + i, , values); // 给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值
}
string savename = @"D:\WordDemo" + DateTime.Now.ToString("yyyyMMdd").Trim() + ".doc";//默认名称
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "doc|*.doc|所有文件|*.*";
saveFileDialog.FilterIndex = ;
saveFileDialog.FileName = savename;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
savename = saveFileDialog.FileName;//设置保存的路径及文件名
}
try
{
report.SaveDocument(savename);//保存文件
MessageBox.Show("保存成功!", "提示");
}
catch(Exception ex)
{
MessageBox.Show("保存失败:"+ex, "提示");
}
}
利用标签导出Word文档的更多相关文章
- 使用Spire.Doc组件利用模板导出Word文档
以前一直是用Office的组件实现Word文档导出,但是让客户在服务器安装Office,涉及到版权:而且Office安装,包括权限配置也是比较麻烦. 现在流行使用第三方组件来实现对Office的操作, ...
- Struts2利用iText导出word文档(包含表格)以提供下载
J2EE ExcelStrutsXML 在公司实习期间,带我的老师让我实现一功能——在显示课表的页面上上点击“导出文件“时能以word文档形式下载课表.将课表导出到excel里的功能他们已经实现了, ...
- 利用NPOI导出Word文档帮助类
/// <summary> /// NPOI操作Word /// </summary> public class NpoiWordHelper { /// <summar ...
- .NET通过调用Office组件导出Word文档
.NET通过调用Office组件导出Word文档 最近做项目需要实现一个客户端下载word表格的功能,该功能是用户点击"下载表格",服务端将该用户的数据查询出来并生成数据到Word ...
- Java 用Freemarker完美导出word文档(带图片)
Java 用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...
- 【Java】用Freemarker完美导出word文档(带图片)
Java 用Freemarker完美导出word文档(带图片) 前言 最近在项目中,因客户要求,将页面内容(如合同协议)导出成word,在网上翻了好多,感觉太乱了,不过最后还是较好解决了这个问题. ...
- freemarker导出word文档——WordXML格式解析
前不久,公司一个项目需要实现导出文档的功能,之前是一个同事在做,做了3个星期,终于完成了,但是在项目上线之后却发现导出的文档有问题,此时,这个同事已经离职,我自然成为接班者,要把导出功能实现,但是我看 ...
- freemarker导出word文档
使用freemarker导出word文档的过程 **************************************************************************** ...
- 【Java】导出word文档之freemarker导出
Java导出word文档有很多种方式,本例介绍freemarker导出,根据现有的word模板进行导出 一.简单导出(不含循环导出) 1.新建一个word文件.如下图: 2.使用word将文件另存为x ...
随机推荐
- natapp 内网穿透服务
参考文章:https://www.jianshu.com/p/91a321e584b8 参考文章:https://www.jianshu.com/p/c4cb8666c96a 一.什么是内网穿透 通过 ...
- pwn之偏移量offset
0x7fffffffdd00: 0x4141414141414141 0x4141414141414141 0x7fffffffdd10: 0x4141414141414141 0x414141414 ...
- SSM-文件上传
因为开发环境和线上环境系统不一样,所以需要区别环境 config.java 可以判断系统进行自动化的区别,我是手动去切换注释的 public class config { //public stati ...
- 「HNOI2008」玩具装箱
传送门 Luogu 解题思路 \(\text{DP}\) 很显然: 设 \(dp_i\) 表示前 \(i\) 个玩具的最小费用,转移就是: \(dp_i = \max\limits_{0\le j & ...
- IDEA 单行注释与代码对齐
效果 修改步骤 Settings -> Editor -> Code Style (1)修改.java文件的注释 comment 评论.注释.意见. (2)修改.html文件的注释 ( ...
- 【Go语言系列】2.2、Go语言基本程序结构:关键字与标识符
什么是标识符 标识符用来命名变量.类型等程序实体.标识符是指Go语言对各种变量.方法.函数等命名时使用的字符序列,标识符由若干个字母.下划线_.和数字组成,且第一个字符必须是字母.通俗的讲就是凡可以自 ...
- CAS实现单点登录(SSO)经典完整教程
转自 http://blog.csdn.net/small_love/article/details/6664831 一.简介 1.cas是有耶鲁大学研发的单点登录服务器 2.本教材所用环境 Tomc ...
- 在React中随机生成图形验证码
各个方法 在输入框中定义一个位置存放图形 完整代码 方便复制粘贴 import React, { Component } from 'react'; import styles from './lef ...
- Java 实现 POS 打印机无驱打印
来源:https://www.ibm.com/developerworks/cn/java/j-lo-pos/index.html 行业需求 我们是一家专业做酒店餐饮软件的公司,餐饮软件一个重要的功能 ...
- Day4 - J - Rank of Tetris HDU - 1811
自从Lele开发了Rating系统,他的Tetris事业更是如虎添翼,不久他遍把这个游戏推向了全球. 为了更好的符合那些爱好者的喜好,Lele又想了一个新点子:他将制作一个全球Tetris高手排行榜, ...