--向Word文档中插入表格--
(1)在OfficeOperator项目的WordOperator类中定义向Word文档插入换页的函数NewPage
(2)在WordOperator类中定义向Word文档插入表格的函数InsertTable
cs
using Microsoft.Office.Interop.Word;// 引入Microsoft.Office.Interop.Word命名空间
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeOperator1
{
public class WordOperator1
{
//为WordOperator1声明两个操作Word文档的私有对象
Application WordApp; //Word应用对象
Document WordDoc; //Word文档对象
public WordOperator1() //在WordOperator1的构造函数中创建WordApp
{
WordApp = new Application(); //创建Word应用对象
WordApp.Visible = true; //创建完成后是否显示Word文档
}
//定义用于创建Word文档的函数CreateWord,代码如下:
public void CreateWord()//创建Word文档
{
WordDoc = WordApp.Documents.Add(); //创建Word文档对象
WordDoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait; //横板还是竖板
WordDoc.PageSetup.LeftMargin = WordApp.CentimetersToPoints(0.5f); //左边距
WordDoc.PageSetup.RightMargin = WordApp.CentimetersToPoints(0.5f); //右边距
WordDoc.PageSetup.TopMargin = WordApp.CentimetersToPoints(0.5f); //上边距
WordDoc.PageSetup.BottomMargin = WordApp.CentimetersToPoints(0.5f); //下边距
WordDoc.PageSetup.PageWidth = 400; //页宽,单位:像素
WordDoc.PageSetup.PageHeight = 600; //页高,单位:像素
}
public void SaveWord(string fileName)//文档保存
{
object FileName = fileName; //文档名称
object FileFormat = WdSaveFormat.wdFormatDocument; //Word文档保存格式
object LockComments = false; //是否锁定批注
object Password = ""; //打开Word文档密码
object WritePassword = ""; //修改Word文档密码
object AddToRecentFiles = true; //是否将文档添加到近期使用的文件菜单中
WordDoc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref Password, ref AddToRecentFiles, ref WritePassword); //保存Word文档
}
public void QuitWord()//关闭Word文档
{
((_Document)WordDoc).Close(); //关闭Word文档
((_Application)WordApp).Quit(); //退出Word应用
}
//退出Word应用程序
public void SetPageHeader(string Text)//页眉中添加文字
{
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; //设置视图类型
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;//选定页眉
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(Text);//向页眉中添加文字
WordApp.Selection.ParagraphFormat.Alignment = //设置居中对齐
WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//选定主文档
}
public void SetPageFooter(string Text)//页脚中添加文字
{
WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; //设置视图类型
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryFooter;//选定页脚
WordApp.ActiveWindow.ActivePane.Selection.InsertAfter(Text); //向页脚中添加文字
WordApp.Selection.ParagraphFormat.Alignment = //设置居中对齐
WdParagraphAlignment.wdAlignParagraphCenter;
WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; //选定主文档
}
/// <summary>
/// 设置页码
/// </summary>
/// <param name="isFirstPage"></param>
public void InsertPageNumber(bool isFirstPage)
{
object Alignment = WdPageNumberAlignment.wdAlignPageNumberRight;//页码对齐方式
object IsFirstPage = isFirstPage; //是否从首页开始
//对所有的页眉和页脚设置页码
WdHeaderFooterIndex WdFooterIndex = WdHeaderFooterIndex.wdHeaderFooterPrimary;
WordApp.Selection.Sections[1].Footers[WdFooterIndex].PageNumbers.Add
(ref Alignment, ref IsFirstPage);
}
/// <summary>
/// Word文档添加文字
/// </summary>
/// <param name="Text"></param>
/// <param name="FontSize"></param>
/// <param name="FontColor"></param>
/// <param name="FontBold"></param>
/// <param name="TextAlignment"></param>
/// <param name="FontName"></param>
public void InsertText(string Text, int FontSize, WdColor FontColor, int FontBold,
WdParagraphAlignment TextAlignment, string FontName)
{
WordApp.Application.Selection.Font.Size = FontSize; //字体大小
WordApp.Application.Selection.Font.Bold = FontBold; //是否粗体,0-否,1-是
WordApp.Application.Selection.Font.Color = FontColor; //字体颜色
WordApp.Application.Selection.ParagraphFormat.Alignment = TextAlignment; //字体排布
WordApp.Application.Selection.Font.Name = FontName; //字体名称
WordApp.Application.Selection.TypeText(Text); //文字内容
}
/// <summary>
/// 换行
/// </summary>
public void NewLine()
{
WordApp.Application.Selection.TypeParagraph(); //换行
}
/// <summary>
/// 向Word文档中插入图片
/// </summary>
/// <param name="FileName"></param>
/// <param name="Width"></param>
/// <param name="Height"></param>
public void InsertPicture(string FileName, int Width, int Height)
{
object LinkToFile = false; //是否连接到文件
object SaveWithDocument = true; //是否保存到文档中
object Range = System.Reflection.Missing.Value;
WordApp.Selection.ParagraphFormat.Alignment = //设置段落对齐方式
WdParagraphAlignment.wdAlignParagraphCenter;
InlineShape inlineShape = WordDoc.Application.Selection.InlineShapes.
AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range); //添加图片
if (Width != 0 || Height != 0)
{
inlineShape.Width = Width; //设置图像宽度
inlineShape.Height = Height; //设置图像高度
}
}
/// <summary>
/// 换页
/// </summary>
public void NewPage()
{
object BreakType = WdBreakType.wdSectionBreakNextPage; //换页
WordDoc.Application.Selection.InsertBreak(ref BreakType); //插入换页
}
/// <summary>
/// 添加表格
/// </summary>
/// <param name="dataSet"></param>
public void InsertTable(DataSet dataSet)
{
WordDoc.Tables.Add(WordApp.Selection.Range, //添加表格
dataSet.Tables[0].Rows.Count, dataSet.Tables[0].Columns.Count);
WordDoc.Tables[1].Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast; //行高规则
WordDoc.Tables[1].Rows.Height = WordApp.CentimetersToPoints(0.8f);//设置行高
WordDoc.Tables[1].Range.Font.Size = 10; //设置字体大小
WordDoc.Tables[1].Range.Font.Name = "宋体"; //设置字体类型
WordDoc.Tables[1].Range.ParagraphFormat.Alignment = //设置段落对齐
WdParagraphAlignment.wdAlignParagraphCenter;
WordDoc.Tables[1].Range.Cells.VerticalAlignment = //设置表格元素垂直对齐
WdCellVerticalAlignment.wdCellAlignVerticalCenter;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderLeft].LineStyle = //设置左边框
WdLineStyle.wdLineStyleDouble;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderRight].LineStyle = //设置右边框
WdLineStyle.wdLineStyleDouble;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderTop].LineStyle = //设置上边框
WdLineStyle.wdLineStyleDouble;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderBottom].LineStyle = //设置下边框
WdLineStyle.wdLineStyleDouble;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderHorizontal].LineStyle = //设置水平边框
WdLineStyle.wdLineStyleSingle;
WordDoc.Tables[1].Borders[WdBorderType.wdBorderVertical].LineStyle = //设置垂直边框
WdLineStyle.wdLineStyleSingle;
//将数据集中的数据填充到表格中
for (int i = 1; i <= dataSet.Tables[0].Rows.Count; i++)
{
for (int j = 1; j <= dataSet.Tables[0].Columns.Count; j++)
{
WordDoc.Tables[1].Cell(i, j).Range.Text = dataSet.Tables[0].Rows[i - 1][j - 1].ToString();
}
}
}
}
}
(3)将数据库中的学生信息表添加到Word文档中。在CreateWord项目的main函数中添加代码如下:
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM student_info",
"Data Source=.\\SQLEXPRESS;Initial Catalog=student;Integrated Security=True");
DataSet dataSet = new DataSet();
adapter.Fill(dataSet); //填充数据集
word.InsertTable(dataSet); //插入表格
cs
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using OfficeOperator1;
namespace CreateWord1
{ internal class Program
{
static void Main(string[] args)
{
WordOperator1 word = new WordOperator1();
word.CreateWord(); //创建Word文档
word.SetPageHeader("C#经典实例"); //添加页眉
word.SetPageFooter("第17章 访问office"); //添加页脚
word.InsertPageNumber(true); //添加页码
word.InsertText("Word文档创建成功!", 16, WdColor.wdColorBlack, 1,
WdParagraphAlignment.wdAlignParagraphCenter, "宋体"); //添加文字
word.NewLine(); //换行
word.InsertText("Word文档创建成功!", 18, WdColor.wdColorRed, 0,
WdParagraphAlignment.wdAlignParagraphDistribute, "黑体"); //添加文字
word.InsertPicture(Directory.GetCurrentDirectory() + "\\189.png", 100, 75);
//添加图片
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM staq_info",
"Data Source=.\\SQLEXPRESS;Initial Catalog=aq;Integrated Security=True");
DataSet dataSet = new DataSet();
adapter.Fill(dataSet); //填充数据集
word.InsertTable(dataSet); //插入表格
word.SaveWord(Directory.GetCurrentDirectory() + "\\测试文档11.doc");//保存Word文档
word.QuitWord();
}
}
}
代码中的aq是数据库,staq是数据表格 ,具体参考数据库章节/两篇代码汇总了word1-3章节
启动CreateWord的控制台应用程序:
--读取Word文档中表格 --
【实现过程】
(1)在OfficeOperator项目的WordOperator类中定义打开Word文档的函数OpenWord
public void OpenWord(string fileName)
{
object FileName = fileName; //Word文档文件名称
WordDoc = WordApp.Documents.Open(ref FileName); //打开Word文档
}
(2)在WordOperator类中定义读取Word文档中表格的函数ReadTable,代码如下:
public string ReadTable()
{
string stringTable = string.Empty;
foreach (Table table in WordDoc.Tables)
{//遍历Word文档中的表格
for (int row = 1; row <= table.Rows.Count; row++)
{//遍历表格中的行
for (int column = 1; column <= table.Columns.Count; column++)
{//遍历表格中的列
stringTable += table.Cell(row, column).Range.Text;//读取表格元素
stringTable = stringTable.Remove(stringTable.Length - 2, 2);//删除\r\a
stringTable += "\t";
}
stringTable += "\n";
}
}
return stringTable;
}
(3)创建一个名为OpenWord的控制台应用程序,为其添加对OfficeOperator项目的引用
cs
using OfficeOperator1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OpenWord
{
internal class Program
{
static void Main(string[] args)
{
WordOperator1 word = new WordOperator1();
word.OpenWord(Directory.GetCurrentDirectory() + "\\测试文档.doc"); //打开Word文档
Console.WriteLine(word.ReadTable()); //读取Word文档中的表格
word.QuitWord();
Console.ReadKey();
}
}
}
(4)在程序路径准备 测试文档.doc(这里是上一章创建保存的文档复制过来):
启动OpenWord的控制台应用程序: