很多的程序都需要用到对word的操作,数据库里面的表需要一书面的形式展示出来,
最近在的一个项

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using Word = Microsoft.Office.Interop.Word;
using Microsoft.Office.Interop.Word;
using System.Windows.Forms;
namespace jiankong
{
public class WorldToos
{
#region - 属性 -
private Microsoft.Office.Interop.Word._Application oWord = null;
private Microsoft.Office.Interop.Word._Document odoc = null;
private Microsoft.Office.Interop.Word._Document oDoc
{
get
{
if (odoc == null)
{
odoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
return odoc;
}
set
{
if (value != null)
{
odoc = value;
}
}
}
private object Nothing = System.Reflection.Missing.Value;
public enum Orientation { 横板, 竖板 }
public enum Alignment { 左对齐, 居中, 右对齐 }
#endregion
#region - 添加文档 -
#region - 创建并打开一个空的word文档进行编辑 -
public void OpenNewWordFileToEdit()
{
oDoc = oWord.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
}
#endregion
#endregion
#region - 创建新Word -
public bool CreateWord(bool isVisible)
{
try
{
oWord = new Microsoft.Office.Interop.Word.Application();
oWord.Visible = isVisible;
return true;
}
catch (Exception)
{
return false;
}
}
public bool CreateWord()
{
return CreateWord(false);
}
#endregion
#region - 打开文档 -
public bool Open(string filePath, bool isVisible)
{
try
{
oWord.Visible = isVisible;
object path = filePath;
oDoc = oWord.Documents.Open(ref path,
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);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入表格 -
public bool InsertTable(DataTable dt, bool haveBorder, double[] colWidths)
{
try
{
object Nothing = System.Reflection.Missing.Value;
int lenght = oDoc.Characters.Count - ;
object start = lenght;
object end = lenght;
//表格起始坐标
Microsoft.Office.Interop.Word.Range tableLocation = oDoc.Range(ref start, ref end);
//添加Word表格
Microsoft.Office.Interop.Word.Table table = oDoc.Tables.Add(tableLocation, dt.Rows.Count,
dt.Columns.Count, ref Nothing, ref Nothing);
if (colWidths != null)
{
for (int i = ; i < colWidths.Length; i++)
{
table.Columns[i + ].Width = (float)(28.5F * colWidths[i]);
}
}
///设置TABLE的样式
table.Rows.HeightRule = Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast; table.Rows.Height = oWord.CentimetersToPoints(float.Parse("0.8"));
table.Range.Font.Size = 10.5F;
table.Range.Font.Name = "宋体";
table.Range.Font.Bold = ;
table.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
table.Range.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
if (haveBorder == true)
{
//设置外框样式
table.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
table.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
//样式设置结束
}
for (int row = ; row < dt.Rows.Count; row++)
{
for (int col = ; col < dt.Columns.Count; col++)
{
table.Cell(row + , col + ).Range.Text = dt.Rows[row][col].ToString();
}
}
return true;
}
catch (Exception e)
{
MessageBox.Show(e.ToString(), "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
finally
{
}
}
public bool InsertTable(DataTable dt, bool haveBorder)
{
return InsertTable(dt, haveBorder, null);
}
public bool InsertTable(DataTable dt)
{ return InsertTable(dt, false, null); }
#endregion
#region - 插入文本 -
public bool InsertText(string strText, System.Drawing.Font font, Alignment alignment, 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 == FontStyle.Bold) { rng.Font.Bold = ; }
//设置单元格中字体为粗体
SetAlignment(rng, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public bool InsertText(string strText)
{
return InsertText(strText, new System.Drawing.Font("宋体", 10.5F, FontStyle.Bold), Alignment.左对齐, false);
}
#endregion
#region - 设置对齐方式 -
private Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)
{
rng.ParagraphFormat.Alignment = SetAlignment(alignment);
return SetAlignment(alignment);
}
private Microsoft.Office.Interop.Word.WdParagraphAlignment SetAlignment(Alignment alignment)
{
if (alignment == Alignment.居中)
{
return Word.WdParagraphAlignment.wdAlignParagraphCenter;
}
else if (alignment == Alignment.左对齐)
{
return Word.WdParagraphAlignment.wdAlignParagraphLeft;
}
else
{ return Word.WdParagraphAlignment.wdAlignParagraphRight; }
}
#endregion
#region - 页面设置 -
public void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
oDoc.PageSetup.PageWidth = oWord.CentimetersToPoints((float)width);
oDoc.PageSetup.PageHeight = oWord.CentimetersToPoints((float)height);
if (orientation == 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 * );//下边距
}
public void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(orientation, , 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
public void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
{
SetPage(Orientation.竖板, , 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
}
#endregion
#region - 插入分页符 -
public void InsertBreak()
{
Word.Paragraph para; para = oDoc.Content.Paragraphs.Add(ref Nothing);
object pBreak = (int)WdBreakType.wdSectionBreakNextPage; para.Range.InsertBreak(ref pBreak);
}
#endregion
#region - 关闭当前文档 -
public bool CloseDocument()
{
try
{
object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
oDoc.Close(ref doNotSaveChanges, ref Nothing, ref Nothing);
oDoc = null;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 关闭程序 -
public bool Quit()
{
try
{
object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;
oWord.Quit(ref saveOption, ref Nothing, ref Nothing);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 保存文档 -
public bool Save(string savePath)
{
return Save(savePath, false);
}
public bool Save(string savePath, bool isClose)
{
try
{
object fileName = savePath;
oDoc.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);
if (isClose)
{
return CloseDocument();
}
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 插入页脚 -
public bool InsertPageFooter(string text, System.Drawing.Font font, WorldToos.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.InsertAfter(text);
GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
return true;
}
catch (Exception)
{
return false;
}
}
public bool InsertPageFooterNumber(System.Drawing.Font font, WorldToos.Alignment alignment)
{
try
{
oWord.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
oWord.Selection.WholeStory();
oWord.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;//页脚
oWord.Selection.TypeText("第");
object page = WdFieldType.wdFieldPage;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref page, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页/共");
object pages = WdFieldType.wdFieldNumPages;
oWord.Selection.Fields.Add(oWord.Selection.Range, ref pages, ref Nothing, ref Nothing);
oWord.Selection.TypeText("页"); GetWordFont(oWord.Selection.Font, font);
SetAlignment(oWord.Selection.Range, alignment);
oWord.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region - 字体格式设定 -
public void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
{
wordFont.Name = font.Name;
wordFont.Size = font.Size;
if (font.Bold) { wordFont.Bold = ; }
if (font.Italic) { wordFont.Italic = ; }
if (font.Underline == true)
{
wordFont.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone;
}
wordFont.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic;
if (font.Strikeout)
{
wordFont.StrikeThrough = ;//删除线
}
}
#endregion
#region - 获取Word中的颜色 -
public WdColor GetWordColor(Color c)
{
UInt32 R = 0x1, G = 0x100, B = 0x10000;
return (Microsoft.Office.Interop.Word.WdColor)(R * c.R + G * c.G + B * c.B);
}
#endregion
XAML 文件:
<Window x:Class="jiankong.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="" >
<Canvas Name="LayOut">
<Canvas Height="" Width="">
<Canvas.Background>
<ImageBrush ImageSource="/jiankong;component/Images/dd2.png" Stretch="Fill"/>
</Canvas.Background>
<Ellipse Width="" Height="" Stroke="Red" Canvas.Left="" Canvas.Top="">
</Ellipse>
<Image Panel.ZIndex="" Width="" Source="/jiankong;component/Images/dd.png" Canvas.Left="" Canvas.Top="" />
<Label Canvas.Left="" Canvas.Top="" Content="表盘读书:" Height="" Name="label1" FontSize="" Width="" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="ge" Width="" Text="" Background="Black" Foreground="Wheat" FontSize="" />
<TextBlock Canvas.Left="" Canvas.Top="" Height="" Name="textBlock1" Text="X1" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="shi" Width="" Text="" Background="#FFEE4646" Foreground="GhostWhite" FontSize="" />
<TextBlock Canvas.Left="" Canvas.Top="" Height="" Name="textBlock2" Text="X10" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="bai" Width="" Text="" Background="#FFCE3D3D" Foreground="#FFEEDFDF" FontSize="" />
<TextBlock Canvas.Left="" Canvas.Top="" Height="" Name="textBlock3" Text="X100" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="qian" Width="" Text="" Foreground="#FFEED5D5" Background="#FFEE2222" FontSize="" />
<TextBlock Canvas.Left="" Canvas.Top="" Height="" Name="textBlock4" Text="X1000" /> </Canvas>
<Canvas Background="Silver">
<Label Canvas.Left="" Canvas.Top="" Content="水表编号:XX" Height="" Name="label2" />
<Label Canvas.Left="" Canvas.Top="" Content="业主姓名: 张XXX" Height="" Name="label3" />
<Label Canvas.Left="" Canvas.Top="" Content="上次抄表时间: 2012-07-25" Height="" Name="label4" />
<Label Canvas.Left="" Canvas.Top="" Content="读数:" Height="" Name="label5" />
<TextBox Canvas.Left="" Canvas.Top="" IsReadOnly="True" Height="" Name="Span" Width="" Text="" />
<Label Canvas.Left="" Canvas.Top="" Content="现水费计价:" Height="" />
<Label Canvas.Left="" Canvas.Top="" Content="元/吨" Height="" Name="label6" />
<Label Canvas.Left="" Canvas.Top="" Content="当前表值:" Height="" Name="label7" />
<Label Canvas.Left="" Canvas.Top="" Content="Label" Height="" Name="lblCurrent" Width="" />
<Button Canvas.Left="" Canvas.Top="" Content="抄表" Height="" Name="button1" Width="" />
<Label Canvas.Left="" Canvas.Top="" Content="" Height="" Name="Last" Width="" />
</Canvas>
<Label Canvas.Left="" Canvas.Top="" Content="水费:" Height="" Name="lblshu" Visibility="Hidden" />
<Label Canvas.Left="" Canvas.Top="" Content="Label" Height="" Name="spanToltal" Visibility="Hidden" />
<Label Canvas.Left="" Canvas.Top="" Content="查表人:" Height="" Name="lblchabiao" Visibility="Hidden" />
<TextBox Canvas.Left="" Canvas.Top="" Height="" Name="txtPenname" Width="" Text="王小虎" Visibility="Hidden" />
<Button Canvas.Left="" Canvas.Top="" Content="打单" Height="" Name="button2" Width="" Click="button2_Click" />
</Canvas>
</Window>
后台cs 文件
[只是个测试Dome]
private void button2_Click(object sender, RoutedEventArgs e)
{
string biaoNumber = label2.Content.ToString();//水表编号
string penName = label3.Content.ToString();//业主姓名
string lastDate = label4.Content.ToString();//上次抄表时间
string begNUmber = Last.Content.ToString();//开始数
string spanNow = this.Span.Text.ToString();//单位价格
string endNumber = this.lblCurrent.Content.ToString();//当前读书
string shuiMoney = this.spanToltal.Content.ToString();//应缴水费
string chkPenser = txtPenname.Text.ToString();//查表人
string dTime = DateTime.Now.Year.ToString() + "年 " + DateTime.Now.Month.ToString() + "月" + "水费缴费单"; WorldToos WordPlayer = new WorldToos();
if (WordPlayer.CreateWord() == false)
{
System.Windows.Forms. MessageBox.Show("文件创造失败.", "错误提示", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
return;
}
DataTable storedt = new DataTable();
storedt.Columns.Add("第一列");
storedt.Columns.Add("第二列");
storedt.Columns.Add("第三列");
storedt.Columns.Add("第四列");
storedt.Rows.Add("水表起始数:", begNUmber, "水表结束数:", endNumber); storedt.Rows.Add("本月用水", yongshui.ToString() + "立方米", "当前计价单位:", spanNow+"立方米/元");
storedt.Rows.Add("本月应收费:", shuiMoney, "查表员:", chkPenser);
storedt.Rows.Add("收费人", "王大用", "付款人签字:", "");
WordPlayer.SetPage(WorldToos.Orientation.横板, 18.4, , , 2.4, 1.87, 2.1);
WordPlayer.InsertText(dTime, new Font("微软雅黑", , System.Drawing.FontStyle.Bold),
jiankong.WorldToos.Alignment.居中, true);
WordPlayer.InsertText(biaoNumber, new Font("微软雅黑", , System.Drawing.FontStyle.Bold),
jiankong.WorldToos.Alignment.居中, true);
WordPlayer.InsertText( penName + " ",
new Font("宋体", , System.Drawing.FontStyle.Regular),
jiankong.WorldToos.Alignment.左对齐, false);
WordPlayer.InsertTable(storedt, true);
WordPlayer.InsertText("查表时间:" + DateTime.Now.ToString(), new Font("宋体", , System.Drawing.FontStyle.Regular), jiankong.WorldToos.Alignment.右对齐, false);
WordPlayer.Save(@"F:" + "\\" + dTime + ".doc", true);
MessageBox.Show("文件已经生成存放到F盘" + dTime+".doc"); }

目里面用到了打印表单,在网上找了写资料整理出来和大家分废话不多说了,咱们看代码

C# /windowForm/WPF/SilverLight里面操作Word帮助类提供给大家的更多相关文章

  1. C#操作Word的+ CKEditor 輸出成Word文件(包含圖案上傳)

    C#操作Word 参考博文: C#操作word类文件 https://www.cnblogs.com/walking/p/3571068.html C#中的Office操作专栏(21) http:// ...

  2. WPF/Silverlight中的RichTextBox总结

    WPF/Silverlight中的RichTextBox总结   在WPF或者是在Silverlight中有个非常强大的可以编辑的容器控件RichTextBox,有的时间会采取该控件来作为编辑控件.鉴 ...

  3. Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架

    Mvvm Light Toolkit for WPF/Silverlight系列之搭建mvvmlight开发框架   本章节,我将通过示例介绍如何搭建mvvmlight开发环境.示例中的我会针对wpf ...

  4. python操作word(改课文格式)【最终版】

    python操作word的一些方法,前面写了一些感悟,有点跑题,改了下题目,方便能搜索到.心急的可以直接拉到最后看代码,我都加了比较详细的注释. 从8.3号早上9点,到8.8号下午5点半下班,终于把这 ...

  5. WPF读取和显示word

    引言 在项目开发中,word的读取和显示会经常出现在客户的需求中.特别是一些有关法律规章制度.通知.红头文件等,都是用word发布的. 在WPF中,对显示WORD没有特定的控件,这对开发显示WORD的 ...

  6. WPF/Silverlight深度解决方案:(六)HLSL自定义渲染特效之完美攻略(上)

    原文:WPF/Silverlight深度解决方案:(六)HLSL自定义渲染特效之完美攻略(上) Shader Effect种位图特效及2种渲染特效,而Silverlight中仅有这2种渲染特效: Bl ...

  7. python操作word入门

    1.安装pywin32 http://sourceforge.net/projects/pywin32 在files里去找适合你的python版本.截止此文,最新版本是pywin32-219快捷路径: ...

  8. XData -–无需开发、基于配置的数据库RESTful服务,可作为移动App和ExtJS、WPF/Silverlight、Ajax等应用的服务端

    XData -–无需开发.基于配置的数据库RESTful服务,可作为移动App和ExtJS.WPF/Silverlight.Ajax等应用的服务端   源起一个App项目,Web服务器就一台,已经装了 ...

  9. C#中操作Word(1)—— word对象模型介绍

    一.开发环境布置 C#中添加对Word的支持,只需添加对Microsoft.Office.Interop.Word的命名空间,如下图所示,右键点击“引用”,在弹出的“添加引用”对话框中选中COM标签页 ...

随机推荐

  1. 关于一些Java基础数据类型的常用方法的应用场景的小思考

    昨天遇到一个问题,按照我的一半解决方法是传一个参数,然后通过参数来控制逻辑处理:但是领导发现String的一个方法也可以完全完成该问题!而我完全没有get到这个点! so,我认识到了自己的知识盲区:基 ...

  2. python Tk()生成的桌面的具体设置方法

    rom tkinter import * root = Tk() root['height'] = 300 #设置高 root['width'] = 500 #设置宽 root.title('魔方小站 ...

  3. Python 进阶 之 函数对象

    Python的世界里,万物皆对象,函数当然也是: 首先要定义一个函数: def add(a,b): print a+b 其次定义一个字典来引用该函数: dic = {"add":a ...

  4. let变量声明总结

    let命令有四大主要特性:存在块级作用域,没有变量提升,暂时性死区,不允许重复声明. 这都是和es5的var变量特性相反的. 1.存在块级作用域 let命令声明的变量只在其块级作用域中有效,就是{}中 ...

  5. 设置iSCSI的发起程序(客户端)(三)

    iSCSI 发起程序是一种用于同 iSCSI 目标器认证并访问服务器上共享的LUN的客户端.我们可以在本地挂载的硬盘上部署任何操作系统,只需要安装一个包来与目标器验证. 初始器客户端设置 功能 可以处 ...

  6. PHP文件操作函数

    1 获得文件名: basename(); 给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名.如果文件名是以 suffix 结束的,那这一部分也会被去掉. eg: 复制代码 代码如下: ...

  7. HDU 2164(模拟)

    Rock, Paper, or Scissors? Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Jav ...

  8. Java中byte与(16进制)字符串的互相转换

    java中byte用二进制表示占用8位,而我们知道16进制的每个字符需要用4位二进制位来表示,所以我们就可以把每个byte转换成两个相应的16进制字符,即把byte的高4位和低4位分别转换成相应的16 ...

  9. 灯泡游戏 (Kruskal)(并查集)

    灯泡游戏 时间限制: 1 Sec  内存限制: 64 MB提交: 9  解决: 4[提交][状态][讨论版] 题目描述 有 一个n行m列的矩阵,左上角坐标是(0,0),右下角坐标是(n-1,m-1). ...

  10. 学习LSM(Linux security module)之三:Apparmor的前世今生和基本使用

    感冒了,感觉一脑子浆糊,真是蛋疼. 先粗略讲一些前置知识. 一:MAC和DAC DAC(Discretionary Access Control),自主访问控制,是最常用的一类访问控制机制,意思为主体 ...