c#生成word报告

这篇具有很好参考价值的文章主要介绍了c#生成word报告。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

有个WPF做的客户端在完成任务后需要出具一份受控报告,详情如下。

目的:根据word模板结合具体数据生成word报告
技术路径:word模板包含书签,生成报告时具体数据替换对应的书签,书签类型有字符串和表格两种。
需求
○ 能够将word书签替换为字符串、表格;
○添加页脚:能够获取当前页面页数,以及总页数

c#生成word报告
现有c# word库调研:
c#生成word报告
综上,优先推荐DocX、Microsoft.Office.Interop.Word,两者主要区别在于是否依赖Office,在使用便利性上DocX优于Microsoft.Office.Interop.Word,DocX操作逻辑上更为简单,但功能上应该还是Microsoft.Office.Interop.Word更全,毕竟Office是成熟的产品,有微软爸爸背书。

最初使用的是Microsoft.Office.Interop.Word,但后来有个客户电脑出word会报如下错误,后来试了几种方法没解决,最后便使用DocX库避免依赖Office解决这个问题。
最后,由于没有深入研究DocX页脚功能,便提前利用Microsoft.Office.Interop.Word制作包含页脚的word模板,然后使用DocX将具体内容(字符串 && 表格)填入并生成word报告。
c#生成word报告

Microsoft.Office.Interop.Word代码

        public void report(ref ReportData reportData, string templatePath, string reportPath)
        {
            if (!File.Exists(templatePath)) return;
            try
            {
                Word.Application app = new Word.Application();
                app.Visible = false;
                Word.Document doc = app.Documents.Open(templatePath);//打开word文件
                object missing = System.Reflection.Missing.Value;

                string allBookMarkString = "";
                foreach (Word.Bookmark bookmark in doc.Bookmarks)
                {
                    allBookMarkString += bookmark.Name;
                    if (bookmark.Name == "RawData")
                    {
                        //Word.Bookmark bk = doc.Bookmarks["RawData"];
                        Word.Range range = bookmark.Range;
                        Word.Table table = doc.Tables.Add(range, 6, 7, ref missing, ref missing);
                        table.Borders.Enable = 1;
                        inserTableData(ref table, ref reportData);
                    }
                }

                Dictionary<string, string> dicData = reportData.ProjectData.getDictionary();
                foreach (var item in dicData)
                {
                    if (item.Value == null) continue;
                    if (allBookMarkString.Contains(item.Key))
                        doc.Bookmarks[item.Key].Range.Text = item.Value;
                }

                setFooter(ref app);

                //保存
                object filename = reportPath;
                doc.SaveAs(ref filename, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing);
                doc.Close(ref missing, ref missing, ref missing);

                if (app != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
                    app = null;
                }
                GC.Collect();
                System.Diagnostics.Process[] excelprocess = System.Diagnostics.Process.GetProcessesByName("WINWORD");
                foreach (System.Diagnostics.Process pr in excelprocess)
                {
                    pr.Kill();//停止关联进程
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("报告生成失败!\n原因: " + ex.Message);
            }

            try
            {
                if (File.Exists(reportPath))
                    CommonFunction.openFile(reportPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("报告打开失败!\n原因: " + ex.Message);
            }            

        }
        //设置页脚
        /*          第   页 共   页
        *               PAGE_OF_
        */               
        void setFooter(ref Word.Application app)
        {
            object missing = System.Reflection.Missing.Value;

            app.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
            app.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            app.ActiveWindow.Selection.TypeText("第");
            Object CurrentPage = Word.WdFieldType.wdFieldPage;
            app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref CurrentPage, ref missing, ref missing);
            app.ActiveWindow.Selection.TypeText("页 共");            
            Object TotalPages = Word.WdFieldType.wdFieldNumPages;
            app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref TotalPages, ref missing, ref missing);
            app.ActiveWindow.Selection.TypeText("页\n");

            /*     Insert current page number "Page X of N" on a word document      */
            /*======================================================================*/
            // Open up the footer in the word document
            app.ActiveWindow.ActivePane.View.SeekView = Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;
            // Set current Paragraph Alignment to Center
            app.ActiveWindow.ActivePane.Selection.Paragraphs.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
            // Type in 'Page '
            app.ActiveWindow.Selection.TypeText("PAGE");
            // Add in current page field
            CurrentPage = Word.WdFieldType.wdFieldPage;
            app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref CurrentPage, ref missing, ref missing);
            // Type in ' of '
            app.ActiveWindow.Selection.TypeText("OF");
            // Add in total page field
            TotalPages = Word.WdFieldType.wdFieldNumPages;
            app.ActiveWindow.Selection.Fields.Add(app.ActiveWindow.Selection.Range, ref TotalPages, ref missing, ref missing);
            /*======================================================================*/

        }

        void inserTableData(ref Word.Table table,ref ReportData reportData)
        {
            try
            {
                if (table == null) return;

                List<string> allNames = reportData.BodySectionData.getAllPointNames(); 
                List<Point_3D> actualPoints = reportData.BodySectionData.getValue(false);
                int nowSectionIndex = reportData.Index;
                List<Point_3D> actualPointsNoBias = reportData.ActualPointsNoBias.GetRange(nowSectionIndex * 4, 4);

                if (allNames.Count != 4 || actualPoints.Count != 4 || actualPointsNoBias.Count != 4)
                    return;
                if (allNames[0] == null || actualPoints[0] == null || actualPointsNoBias[0] == null)
                    return;

                try
                {
                    //设置表格标题
                    table.Cell(1, 1).Range.Text = "水平测量点";
                    table.Cell(1, 5).Range.Text = "实测值(去偏置)";
                    table.Cell(1, 2).Range.Text = "实测值(带偏置)";
                }
                catch (Exception e)
                {
                    MessageBox.Show("表格标题设置出现错误!");
                }

                //合并单元格
                table.Cell(1, 1).Merge(table.Cell(2, 1));
                table.Cell(1, 5).Merge(table.Cell(1, 7));
                table.Cell(1, 2).Merge(table.Cell(1, 4));
                
                for (int i = 0; i < 2; i++)
                {
                    table.Cell(2, i * 3 + 4).Range.Text = "Z(mm)";
                    table.Cell(2, i * 3 + 2).Range.Text = "X(mm)";
                    table.Cell(2, i * 3 + 3).Range.Text = "Y(mm)";
                }

                table.Cell(3, 1).Range.Text = allNames[0];
                table.Cell(4, 1).Range.Text = allNames[1];
                table.Cell(5, 1).Range.Text = allNames[2];
                table.Cell(6, 1).Range.Text = allNames[3];


                insertPoints(ref table, ref actualPoints, 3, 2);
                insertPoints(ref table, ref actualPointsNoBias, 3, 5);  
                
            }
            catch (Exception ex)
            {
                MessageBox.Show("Word 插入表格错误: " + ex.Message);
                return;
            }
            
        }
        
        void insertPoints(ref Word.Table table,ref List<Point_3D> points, int beginRow, int beginCol)
        {

            for(int row= beginRow, index=0; index< points.Count;row++,index++)
            {
                if (points[index] == null)
                    return;

                table.Cell(row, beginCol).Range.Text = String.Format("{0:f3}", points[index].x);
                table.Cell(row, beginCol + 1).Range.Text = String.Format("{0:f3}", points[index].y);
                table.Cell(row, beginCol + 2).Range.Text = String.Format("{0:f3}", points[index].z);
            }
        }


DocX代码

    class DocXHelper
    {
        public DocXHelper()
        {
            //string exePath = System.AppDomain.CurrentDomain.BaseDirectory;
            //string readPath = exePath + "Word-Template.docx";
            //string savePath = exePath + "copyFile.docx";
            //report(readPath, savePath);
            //MessageBox.Show(" 完成!");
        }


        public void report(ref ReportData reportData, string templatePath, string reportPath)
        {
            if (!File.Exists(templatePath)) return;
            using (var document = DocX.Load(templatePath))
            {

                Dictionary<string, string> dicData = reportData.ProjectData.getDictionary();
                foreach (var bookmark in document.Bookmarks)
                {
                    if (bookmark.Name == "RawData")
                    {
                        try
                        {
                            Table table = bookmark.Paragraph.InsertTableBeforeSelf(6, 7);//插入段落后
                            table.Design = TableDesign.TableGrid;
                            table.Alignment = Alignment.center;
                            table.AutoFit = AutoFit.Contents;
                            inserTableData(table, ref reportData);
                        }
                        catch(Exception e)
                        {
                            MessageBox.Show("DocX生成报告失败!", "提示");
                        }
                        
                    }
                    else
                    {
                        if(dicData.ContainsKey(bookmark.Name))
                            bookmark.Paragraph.Append(dicData[bookmark.Name]);
                    }
                }

                
                document.SaveAs(reportPath);  //document.SaveAs(outFile);
                try
                {
                    if (File.Exists(reportPath))
                        CommonFunction.openFile(reportPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("报告打开失败!\n原因: " + ex.Message);
                }

            }
        }


        void inserTableData(Table table, ref ReportData reportData)
        {
            try
            {
                if (table == null) return;

                List<string> allNames = reportData.BodySectionData.getAllPointNames();
                List<Point_3D> actualPoints = reportData.BodySectionData.getValue(false);
                int nowSectionIndex = reportData.Index;
                List<Point_3D> actualPointsNoBias = reportData.ActualPointsNoBias.GetRange(nowSectionIndex * 4, 4);

                if (allNames.Count != 4 || actualPoints.Count != 4 || actualPointsNoBias.Count != 4)
                    return;
                if (allNames[0] == null || actualPoints[0] == null || actualPointsNoBias[0] == null)
                    return;

                try
                { 
                    //设置表格标题
                    setCellText(table, 1, 1, "水平测量点");
                    setCellText(table, 1, 2, "实测值(带偏置)");
                    setCellText(table, 1, 5, "实测值(去偏置)");

                    mergeCol(table, 1, 1, 2);
                    mergeRow(table, 1, 5, 7);
                    mergeRow(table, 1, 2, 4);

                }
                catch (Exception e)
                {
                    MessageBox.Show("表格标题设置出现错误!");
                }

                for (int i = 0; i < 2; i++)
                {
                    setCellText(table, 2, i * 3 + 2, "X(mm)");
                    setCellText(table, 2, i * 3 + 3, "Y(mm)");
                    setCellText(table, 2, i * 3 + 4, "Z(mm)");
                }

                for (int i=0;i< allNames.Count;i++)
                    setCellText(table, 3 + i, 1, allNames[i]);

                insertPoints(ref table, ref actualPoints, 3, 2);
                insertPoints(ref table, ref actualPointsNoBias, 3, 5);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Word 插入表格错误: " + ex.Message);
                return;
            }
        }

        void insertPoints(ref Table table, ref List<Point_3D> points, int beginRow, int beginCol)
        {
            for (int row = beginRow, index = 0; index < points.Count; row++, index++)
            {
                if (points[index] == null)
                    return;

                setCellText(table, row, beginCol, String.Format("{0:f3}", points[index].x));
                setCellText(table, row, beginCol + 1, String.Format("{0:f3}", points[index].y));
                setCellText(table, row, beginCol + 2, String.Format("{0:f3}", points[index].z));
            }
        }


        //row and col are counted from 1
        void mergeRow(Table table, int mergeRow,int beginCol,int endCol)
        {
            if (mergeRow > table.RowCount || beginCol > table.ColumnCount || endCol > table.ColumnCount) return;
            table.Rows[mergeRow - 1].MergeCells(beginCol - 1, endCol - 1);
        }


        //row and col are counted from 1
        void mergeCol(Table table, int mergeCol, int beginRow, int endRow)
        {
            if (mergeCol > table.ColumnCount || beginRow > table.RowCount || endRow > table.RowCount) return;
            table.MergeCellsInColumn(mergeCol - 1, beginRow - 1, endRow - 1);
        }

        //row and col are counted from 1
        void setCellText(Table table,int row,int col,string data)
        {
            table.Rows[row-1].Cells[col-1].Paragraphs[0].Append(data).Alignment = Alignment.center;
        }

    }//DocXHelper

以上的DocX、Microsoft.Office.Interop.Word仅供参考,直接复制肯定跑不通

参考

NPOI.XWPF允许用户操作.docx格式
Aspose.Words for .NET(无需依赖第三方应用,例如Microsoft Word, 或Office Automation,但是收费,慎用!)
Spire.Doc for .NET(收费)
c# Library for manipulating Word documents文章来源地址https://www.toymoban.com/news/detail-479092.html

到了这里,关于c#生成word报告的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • c#客户端Kafka的使用方法

    Apache Kafka是一个分布式流处理平台,最初由LinkedIn开发,现在是Apache软件基金会的顶级项目之一。Kafka能够处理大规模的实时数据流,支持高可靠性、高可扩展性、低延迟和高吞吐量。它主要用于构建实时数据管道和流式处理应用程序。 Kafka的核心概念包括:Producer(生产者)

    2024年02月12日
    浏览(50)
  • 基于C#的ModbusTcp客户端Demo

            今天跟大家分享一个基于C#的ModbusTcp客户端的创建,本人小白一枚,第一次发表博客,有诸多不足之处,还请谅解,也希望大佬可以指点,如何可以做得更好。 先展示一下成品效果吧。         Demo看起来就跟上图一样,这里ui使用了sunnyui的一些控件,以及运用

    2024年02月11日
    浏览(40)
  • 微信小程序错误error:用户绑定的手机号需要验证,请在客户端完成短信

    获取手机号能力,参考官方文档。 用户绑定的手机号需要验证,请在客户端完成短信 在微信开发者工具中点 预览 在手机上打开微信,扫一扫 预览二维码 。 在开发版小程序(扫码预览二维码打开的是开发版小程序)中,点击需要获取手机号的功能。此时,进入验证手机号的

    2024年02月08日
    浏览(140)
  • C# WebSocket 客户端 使用 TouchSocket WebSocketClient

    由于涉及到连接某音的弹幕数据,所以需要WebSocket,百度了一圈,有C#原生的WebSocket,看了看,看不懂,无奈换一个,TouchSocket来到了我的面前,网上对于这个插件的评价较高,所以使用之。结果,一堆问题之。唉。抄袭这么难吗? 如果由TouchSocket开发服务端,并且用TouchSoc

    2024年02月12日
    浏览(41)
  • idea生成wsdl客户端文件

    1.idea安装插件 Jakarta EE: Web Services ​(JAX-WS)​ 2.新建java maven项目,pom文件加入相关依赖文件 选择生成代码的文件,点击Tools-XML Webservice and WSDL-Generate Java Code 4.填写wsdl访问路径及生成文件的包名,点击ok生成相关文件 5.编写代码进行调用

    2024年02月15日
    浏览(29)
  • Idea+maven+springboot项目搭建系列--2 整合Rabbitmq完成客户端&服务器端消息收发

    前言:本文通过springBoot -maven 框架,对Rabbitmq 进行整合,完成客户端消息的发送和消费; 1 为什么要使用Rabbitmq: RabbitMQ 是一个可靠的、灵活的、开源的消息中间件,具有以下优点: 异步通信:RabbitMQ 支持异步通信,使得消息发送者和接收者能够异步处理,提高了系统性能和

    2024年02月07日
    浏览(43)
  • C# socket——简单的TCP 客户端 连接通信

    TCP编程的客户端一般步骤是: 1、创建一个socket,用函数socket()。 2、设置socket属性。 3、设置要连接的对方的IP地址和端口等属性。 4、连接服务器,用函数connect()。 5、收发数据,用函数send()和recv(),或者read()和write()。 6、关闭网络连接。 using System; using System.Net; using System.

    2024年02月11日
    浏览(33)
  • C# 客户端程序 Visual Studio 远程调试方法

    传统桌面客户端的远程调试相比 UWP , ASP 等项目来说,配置比较麻烦,因为它是非部署的应用程序,原理是复制编译的文件到远程计算机,通过网络来连接和 VS 的通信,本文主要讲述 WPF , WinForm 应用程序的远程调试。 下载适合 Visual Studio 版本的最新远程工具。 最新的远程工

    2024年02月08日
    浏览(41)
  • 使用idea如何生成webservice客户端

    需求阐述 在和外围系统对接的时候,对方只给了wsdl地址,记得之前了解到的webservice,可以用idea生成客户端代码。先记录生成的步骤 我的idea再右键要生成文件目录里面没有webservice选项,只能通过查找功能找到 generate Java Code From WSDL功能。 打开功能,我们需要填充3项内容:

    2024年02月14日
    浏览(32)
  • 基于C# Socket实现的简单的Redis客户端

         Redis 是一款强大的高性能键值存储数据库,也是目前 NOSQL 中 最流行 比较流行的一款数据库,它在广泛的应用场景中扮演着至关重要的角色,包括但不限于缓存、消息队列、会话存储等。在本文中,我们将介绍如何基于 C# Socket 来实现一个简单的Redis客户端类 RedisClien

    2024年02月05日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包