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

embedded/2024/10/11 11:24:19/
 --向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.ppmy.cn/embedded/34814.html

相关文章

android TV app适配遥控器思路,recycleview选中放大

背景&#xff1a; 当遥控器遥控盒子&#xff0c;app内是有一套机制&#xff0c;响应遥控器的操作&#xff0c; 需要做的就是&#xff1a; 1、activity中&#xff0c;普通view的处理&#xff1a; 直接监听该view的“setOnFocusChangeListener”方法&#xff0c;如下&#xff1…

文件加密软件排行榜前四名(2024年4大好用的加密软件推荐)

说到文件加密&#xff0c;想必大家都很熟悉&#xff0c;文件加密已经普遍应用&#xff0c;文件加密是一种重要的安全措施&#xff0c;可以确保数据的机密性、完整性和可用性&#xff0c;降低因数据泄露或丢失带来的风险 。 下面小编给大家分享几款常用的加密软件&#xff0c;…

Magic Studio Eraser API使用教程

AI橡皮擦 - 使用网址 Magic Studio的AI橡皮擦功能非常好用&#xff0c;能去除图片中的杂物。但是网页版只支持低分辨率下载&#xff0c;想要原图就得开会员&#xff0c;价格不菲。 不过官网其实提供了API接入方式&#xff0c;并且有100次的免费试用机会 API接入网站 在这里可…

OpenVoice——强大的语音克隆与生成技术

OpenVoice 是一款由 MyShell TTS 开发的令人惊叹的技术。它只需一小段参考发言者的音频片段&#xff0c;就能精确复制其声音&#xff0c;并能够生成多种语言的语音。 其主要功能包括准确的音色克隆&#xff0c;能够精确地克隆参考音色&#xff0c;并在多种语言和口音中生成语音…

【notes2】并发,IO,内存

文章目录 1.线程/协程/异步&#xff1a;并发对应硬件资源是cpu&#xff0c;线程是操作系统如何利用cpu资源的一种抽象2.并发&#xff1a;cpu&#xff0c;线程2.1 可见性&#xff1a;volatile2.2 原子性&#xff08;读写原子&#xff09;&#xff1a;AtomicInteger/synchronized…

doris be报错:sysctl -w vm.max_map_count=2000000

报错信息 [ERROR] 2024-05-06 16:42:18 TaskLogLogger-DORIS-DorisBE:[197] - [INFO] 2024-05-06 16:42:18 TaskLogLogger-DORIS-DorisBE:[175] - execute shell command : [bash, be/bin/start_be.sh, --daemon] [INFO] 2024-05-06 16:42:18 TaskLogLogger-DORIS-DorisBE:[1…

小土堆pytorch学习

土堆视频链接 1. 两大函数 1.1 dir函数 dir函数返回一个属性列表,其中列表的元素都是字符串格式。 对于模块对象:返回模块的所有属性(变量名和方法) 对于类对象:返回这个类的属性,以及其所有父类(包括父类的父类)的属性 对于其它对象(实例对象):返回这个实例…

2024年5月6日优雅草蜻蜓API大数据服务中心v2.0.3更新

v2.0.3更新 2024年5月6日优雅草蜻蜓API大数据服务中心v2.0.3更新-修复改版后搜索框漏掉的bug-增加搜索框 提示&#xff1a;优雅草大数据中心已经 上线137天 稳定运行 1181555 次 累积调用 目前大数据中心用户呈现增长趋势&#xff0c;目标2024年11月底突破1亿次调用&#xf…