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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/588178.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Day27:阻塞队列、Kafka入门、发送系统通知、显示系统

阻塞队列BlockingQueue BlockingQueue 解决线程通信的问题。阻塞方法:put、take。 生产者消费者模式 生产者:产生数据的线程。消费者:使用数据的线程。 &#xff08;Thread1生产者&#xff0c;Thread2消费者&#xff09; 实现类 ArrayBlockingQueueLinkedBlockingQueuePr…

MATLAB 数据导入

MATLAB 数据导入&#xff08;ImportData&#xff09; 在MATLAB中导入数据意味着从外部文件加载数据。该importdata功能允许加载不同格式的各种数据文件。它具有以下五种形式 序号 功能说明 1 A importdata(filename) 从filename表示的文件中将数据加载到数组A中。 2 A i…

Electron+Vue3+Vite+ElectronForge整合-全部ts开发 - 一键启动两个服务 一键打包两个服务

说明 本文介绍一下 Electron Vue3 Vite Electron Forge 的高级整合操作。vue3 : 使用 TS 的语法开发&#xff1b; Electron : 使用 TS 的语法开发。 补充 &#xff1a; 目前Electron的开发还是以JS为主&#xff0c;不过我们可以直接使用TS开发&#xff0c;在执行和打包时&a…

UE5 蓝图入门

基础节点创建&#xff1a; 常量&#xff1a; 按住 1 &#xff0c;点击鼠标左键&#xff0c;创建常量 二维向量&#xff1a; 按住 2 &#xff0c;点击鼠标左键&#xff0c;创建二维向量 三维向量&#xff1a; 按住 3 &#xff0c;点击鼠标左键 按 c 键打出一个注释框 参考视…

C# Winform父窗体打开新的子窗体前,关闭其他子窗体

随着Winform项目越来越多&#xff0c;界面上显示的窗体越来越多&#xff0c;窗体管理变得更加繁琐。有时候我们要打开新窗体&#xff0c;然后关闭多余的其他窗体&#xff0c;这个时候如果一个一个去关闭就会变得很麻烦&#xff0c;而且可能还会出现遗漏的情况。这篇文章介绍了三…

HR招聘测评,如何进行人才测评?

说起“人才测评”几个字&#xff0c;相信大家都不会陌生&#xff0c;很多人&#xff0c;尤其是求职者来说&#xff0c;则更加熟悉。在求职应聘中&#xff0c;已经有越来越多的企业开始采用人才测评进行人员选拔。了解人才测评的含义&#xff0c;知道人才测评如何进行&#xff0…

打破失联困境:门店如何利用AI智能名片B2B2C商城小程序重构与消费者的紧密连接?

在如今这个消费者行为日益碎片化的时代&#xff0c;门店经营者们时常感叹&#xff1a;消费者进店如同一场不期而遇的缘分&#xff0c;然而一旦离开门店&#xff0c;就仿佛消失在茫茫人海中&#xff0c;难以再觅其踪迹。这种“进店靠缘分&#xff0c;离店就失联”的困境&#xf…

本地大语言模型LLM的高效运行专家 | Ollama

Ollama简介 Ollama是一个开源的大型语言模型服务工具&#xff0c;它帮助用户快速在本地运行大模型。通过简单的安装指令&#xff0c;用户可以执行一条命令就在本地运行开源大型语言模型&#xff0c;如Llama 2。Ollama极大地简化了在Docker容器内部署和管理LLM的过程&#xff0…

平面模型上提取凸凹多边形------pcl

平面模型上提取凸凹多边形 pcl::PointCloud<pcl::PointXYZ>::Ptr PclTool::ExtractConvexConcavePolygons(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) {pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_filtered(new pcl::PointCloud<pcl::PointXYZ>);p…

政安晨:【Keras机器学习示例演绎】(二十八)—— 使用 卷积神经网络与循环神经网络 架构进行视频分类

目录 数据收集 设置 定义超参数 数据准备 序列模型 推论 政安晨的个人主页&#xff1a;政安晨 欢迎 &#x1f44d;点赞✍评论⭐收藏 收录专栏: TensorFlow与Keras机器学习实战 希望政安晨的博客能够对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正…

Android Handler用法

Android Handler用法 为什么要设计Handler机制&#xff1f;Handler的用法1、创建Handler2、Handler通信2.1 sendMessage 方式2.2 post 方式 Handler常用方法1、延时执行2、周期执行 HandlerThread用法主线程-创建Handler子线程-创建Handler FAQMessage是如何创建主线程中Looper…

微服务保护和分布式事务(Sentinel、Seata)笔记

一、雪崩问题的解决的服务保护技术了解 二、Sentinel 2.1Sentinel入门 1.Sentinel的安装 &#xff08;1&#xff09;下载Sentinel的tar安装包先 &#xff08;2&#xff09;将jar包放在任意非中文、不包含特殊字符的目录下&#xff0c;重命名为 sentinel-dashboard.jar &…

Docker容器---Harbor私有仓库部署与管理

一、搭建本地私有仓库 1、下载registry镜像 [rootlocalhost ~]#docker pull registry Using default tag: latest latest: Pulling from library/registry 79e9f2f55bf5: Pull complete 0d96da54f60b: Pull complete 5b27040df4a2: Pull complete e2ead8259a04: Pull comp…

vulnhub靶场之FunBox-1

一.环境搭建 1.靶场描述 Boot2Root ! This is a reallife szenario, but easy going. You have to enumerate and understand the szenario to get the root-flag in round about 20min. This VM is created/tested with Virtualbox. Maybe it works with vmware. If you n…

NASA数据集——NASA 标准二级(L2)暗目标(DT)气溶胶产品每 6 分钟在全球范围内对陆地和海洋上空的气溶胶光学厚度(AOT)产品

VIIRS/NOAA20 Dark Target Aerosol 6-Min L2 Swath 6 km 简介 NOAA-20&#xff08;前身为联合极地卫星系统-1&#xff08;JPSS-1&#xff09;&#xff09;--可见红外成像辐射计套件&#xff08;VIIRS&#xff09;NASA 标准二级&#xff08;L2&#xff09;暗目标&#xff08;D…

集合的基本操作

集合&#xff1a; 在java当中&#xff0c;含有着一些不同的存储数据的相关集合。分为单列集合&#xff08;Collection&#xff09;和双列集合(Map)。 Collection 首先学习Collection来进行展示&#xff1a; 以框框为例子&#xff0c;蓝色的代表的是接口&#xff0c;而红色的…

【Linux极简教程】常见实用命令不断更新中......

【Linux极简教程】常见实用命令不断更新中...... 常见问题1.Waiting for cache lock: Could not get lock /var/lib/dpkg/lock. It is held by process xxxx(dpkg) 常见问题 1.Waiting for cache lock: Could not get lock /var/lib/dpkg/lock. It is held by process xxxx(dp…

机器学习:基于Sklearn、XGBoost,使用逻辑回归、支持向量机和XGBClassifier预测股票价格

前言 系列专栏&#xff1a;机器学习&#xff1a;高级应用与实践【项目实战100】【2024】✨︎ 在本专栏中不仅包含一些适合初学者的最新机器学习项目&#xff0c;每个项目都处理一组不同的问题&#xff0c;包括监督和无监督学习、分类、回归和聚类&#xff0c;而且涉及创建深度学…

C语言——队列的实现

队列按照先进先出&#xff08;FIFO&#xff0c;First In First Out&#xff09;的原则管理数据。这意味着最先进入队列的元素会被最先移出&#xff0c;类似于排队等候服务的情况。队列通常有两个主要操作&#xff1a;入队&#xff08;enqueue&#xff09;&#xff0c;将元素添加…

DSP实时分析平台设计方案:924-6U CPCI振动数据DSP实时分析平台

6U CPCI振动数据DSP实时分析平台 一、产品概述 基于CPCI结构完成40路AD输入&#xff0c;30路DA输出的信号处理平台&#xff0c;处理平台采用双DSPFPGA的结构&#xff0c;DSP采用TI公司新一代DSP TMS320C6678&#xff0c;FPGA采用Xilinx V5 5VLX110T-1FF1136芯片&#xff…
最新文章