c#&word文档:3.向Word文档中插入表格/4.读取Word文档中表格

 --向Word文档中插入表格--

(1)在OfficeOperator项目的WordOperator类中定义向Word文档插入换页的函数NewPage

(2)在WordOperator类中定义向Word文档插入表格的函数InsertTable

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);                                         //插入表格

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项目的引用

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的控制台应用程序:

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在C#处理Word文档表格,可以使用Microsoft.Office.Interop.Word命名空间提供的API进行操作。以下是一个示例代码,可以在Word文档的指定位置创建一个表格,并设置表格的行列数、表头和内容: ```csharp using System; using Microsoft.Office.Interop.Word; namespace WordTableDemo { class Program { static void Main(string[] args) { // 创建Word文档对象 Application wordApp = new Application(); Document wordDoc = wordApp.Documents.Add(); // 在指定位置插入表格 Range range = wordDoc.Range(0, 0); Table table = wordDoc.Tables.Add(range, 4, 3); // 设置表头 table.Cell(1, 1).Range.Text = "姓名"; table.Cell(1, 2).Range.Text = "年龄"; table.Cell(1, 3).Range.Text = "性别"; // 设置表格内容 table.Cell(2, 1).Range.Text = "张三"; table.Cell(2, 2).Range.Text = "18"; table.Cell(2, 3).Range.Text = "男"; table.Cell(3, 1).Range.Text = "李四"; table.Cell(3, 2).Range.Text = "20"; table.Cell(3, 3).Range.Text = "女"; table.Cell(4, 1).Range.Text = "王五"; table.Cell(4, 2).Range.Text = "22"; table.Cell(4, 3).Range.Text = "男"; // 保存Word文档 wordDoc.SaveAs2(@"D:\test.docx"); wordDoc.Close(); // 关闭Word应用程序 wordApp.Quit(); } } } ``` 在上述代码,我们首先创建了一个Word文档对象,然后通过`Range`对象在指定位置插入了一个4行3列的表格。接着,我们通过`table.Cell(row, column)`方法获取表格某个单元格,并设置了表头和表格内容。最后,我们将Word文档保存到本地,并关闭Word应用程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值