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

news/2024/5/20 21:48:01
 --向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.mrgr.cn/p/51415433

相关文章

30分钟彻底了解Flutter整个渲染流程(超详细)

30分钟彻底了解Flutter整个渲染流程[超详细] 从运行第一行代码出发WidgetsFlutterBinding初始化了一堆娃 三个中流砥柱SchedulerBindingRendererBindingWidgetsBinding 申请Vsync流程下发Vsync承接Vsync 从运行第一行代码出发 void main() {runApp(const MyApp()); }void runA…

linux中进程相关概念(一)

什么是程序&#xff0c;什么是进程&#xff0c;有什么区别&#xff1f; 程序是静态的概念&#xff0c;当我们使用gcc xxx.c -o pro进行编译时&#xff0c;产生的pro文件&#xff0c;就是一个程序。 进程是程序的一次运行活动&#xff0c;通俗点就是说程序跑起来了就是进程。 …

C++反汇编,指针和内存分配细节,面试题05

文章目录 20. 指针 vs 引用21. new vs malloc 20. 指针 vs 引用 指针是实体&#xff0c;占用内存空间&#xff0c;逻辑上独立&#xff1b;引用是别名&#xff0c;与变量共享内存空间&#xff0c;逻辑上不独立。指针定义时可以不初始化&#xff1b;引用定义时必须初始化。指针的…

Vue自定义封装音频播放组件(带拖拽进度条)

Vue自定义封装音频播放组件&#xff08;带拖拽进度条&#xff09; 描述 该款自定义组件可作为音频、视频播放的进度条&#xff0c;用于控制音频、视频的播放进度、暂停开始、拖拽进度条拓展性极高。 实现效果 具体效果可以根据自定义内容进行位置调整 项目需求 有播放暂停…

localhost 重定向次数过多

在完成javaweb作业时出现了错误初始页面只有两个功能, 但是无论是点击登录还是注册,都会跳转到login.jsp页面从网上找到的答案是代码陷入死循环,因为总是跳转到login.jsp, 所以我查看了所有servlet类中跳转到login.jsp页面的代码,逻辑上并没有问题;然后我又查看了过滤器以…

Windows平台使用CMake+MinGW64编译OpenCV

Windows平台使用CMake+MinGW64编译OpenCV (注:2年前写的笔记, 可能有些地方过时了) 目录Windows平台使用CMake+MinGW64编译OpenCV1.安装及配置环境1.1 MinGW-w641.2 CMake1.3 OpenCV源码2.CMake配置及生成2.1 新建目录2.2 CMake-GUI2.3 编译配置2.4 生成2.5 Make编译和安装3.配…

【大模型赋能开发者】海云安入选数世咨询LLM驱动数字安全2024——AI安全系列报告

近日&#xff0c;国内知名数字产业领域第三方调研咨询机构数世咨询发布了LLM驱动数字安全2024——AI安全系列报告。报告通过调研、公开信息收集等方式对目前十余家已具备LLM相关的应用能力安全厂商对比分析出了这一领域当前的产业现状并进行了各厂商的能力展示。 海云安凭借近…

金融业开源软件应用 评估规范

金融业开源软件应用 评估规范 1 范围 本文件规定了金融机构在应用开源软件时的评估要求&#xff0c;对开源软件的引入、维护和退出提出了实现 要求、评估方法和判定准则。 本文件适用于金融机构对应用的开源软件进行评估。 2 规范性引用文件 下列文件中的内容通过文中的规范…

介绍适用于 Node.js 的 Elastic OpenTelemetry 发行版

作者&#xff1a;来自 Elastic Trent Mick 我们很高兴地宣布推出 Elastic OpenTelemetry Distribution for Node.js 的 alpha 版本。 该发行版是 OpenTelemetry Node.js SDK 的轻量级包装&#xff0c;可以让你更轻松地开始使用 OpenTelemetry 来观察 Node.js 应用程序。 背景 …

x64dbg中类似于*.exe+地址偏移

在CE和xdb中&#xff0c;形如*.exe数字偏移形式的地址被称为模块地址&#xff0c;CE附加到进程后点击查看内存&#xff0c;显示如下图 这种地址学名叫做模块地址&#xff0c;在x64dbg中显示如下图&#xff1a; CE中可以关闭&#xff0c;从而显示绝对的虚拟地址&#xff0c;如下…

时间复杂度空间复杂度 力扣:转轮数组,消失的数字

1. 算法效率 如何衡量一个算法的好坏&#xff1f;一般是从时间和空间的维度来讨论复杂度&#xff0c;但是现在由于计算机行业发展迅速&#xff0c;所以现在并不怎么在乎空间复杂度了下面例子中&#xff0c;斐波那契看上去很简洁&#xff0c;但是复杂度未必如此 long long Fib…

【JavaEE网络】HTTP响应详解:状态码、报头与正文的全面解析

目录 HTTP响应&#xff08;Response&#xff09;认识 "状态码" (status code)认识响应 “报头”&#xff08;header&#xff09;认识响应 “正文”&#xff08;body&#xff09; HTTP响应&#xff08;Response&#xff09; 响应&#xff1a; 首行响应头空行正文 认…

MySQL#MySql表的操作

目录 一、创建表 二、查看表结构 三、修改表 1.修改表的名字 2.新增一个列 3.修改列 4.删除列 5.修改列的名称 四、删除表 一、创建表 语法&#xff1a; CREATE TABLE table_name (field1 datatype,field2 datatype,field3 datatype ) character set 字符集 collate 校…

一键实现在VS Code中绘制流程图

VS Code是一款常用的IDE&#xff0c;受到许多用户的欢迎和喜爱。而其较为出众的一点&#xff0c;就是较好的可拓展性&#xff0c;即丰富的插件应用&#xff0c;这些应用可以极大地提高生产效率&#xff0c;并优化日常使用。 流程图是一种直观的图示方法&#xff0c;可以用简明…

jsp 实验12 servlet

一、实验目的 掌握怎样在JSP中使用javabean 二、实验项目内容&#xff08;实验题目&#xff09; 编写代码&#xff0c;掌握servlet的用法。【参考课本 上机实验1 】 三、源代码以及执行结果截图&#xff1a; 源代碼&#xff1a; inputVertex.jsp&#xff1a; <% page lang…

[转帖]TLAB(Thread Local Allocation Buffer)

https://www.cnblogs.com/Chary/p/18034613 TLAB是虚拟机在堆内存的eden划分出来的一块专用空间,是线程专属的。在虚拟机的TLAB功能启动的情况下,在线程初始化时,虚拟机会为每个线程分配一块TLAB空间,只给当前线程使用,这样每个线程都单独拥有一个空间,如果需要分配内存,…

【前端】CSS基础(1)

文章目录 前言一、CSS基础1、 CSS是什么2、 CSS基本语法规范3、 代码风格3.1 样式格式3.2 样式大小写3.3 空格规范 4、 CSS引入方式4.1 内部样式表4.2 行内样式表4.3 外部样式 前言 这篇博客仅仅是对CSS的基本结构进行了一些说明&#xff0c;关于CSS的更多讲解以及HTML、Javasc…

YOLOv5改进 | 独家创新篇 | 利用MobileNetV4的UIB模块二次创新C3(全网独家首发)

一、本文介绍 本文给大家带来的改进机制是利用MobileNetV4的UIB模块二次创新C3&#xff0c;其中UIB模块来自2024.5月发布的MobileNetV4网络&#xff0c;其是一种高度优化的神经网络架构&#xff0c;专为移动设备设计。它最新的改动总结主要有两点&#xff0c;采用了通用反向瓶…

OpenHarmony 3.2 Release版本实战开发——Codec HDI适配过程

简介 OpenHarmony Codec HDI&#xff08;Hardware Device Interface&#xff09;驱动框架基于 OpenMax 实现了视屏硬件编解码驱动&#xff0c;提供 Codec 基础能力接口供上层媒体服务调用&#xff0c;包括获取组件编解码能力、创建组件、参数设置、数据的轮转和控制、以及销毁…

GPU通用计算介绍

谈到 GPU &#xff08;Graphics Processing Unit&#xff0c;图形显示卡&#xff09;大多数人想到的是游戏、图形渲染等这些词汇&#xff0c;图形处理确实是 GPU 的一大应用场景。然而人们也早已关注到它在通用计算上的巨大潜力&#xff0c;并提出了 GPGPU (General-purpose co…