OpenXML显示System.NullReferenceException:“对象引用未设置为对象的实例。”在text.Text上

时间:2019-10-28 14:45:08

标签: c# sql-server openxml

我有一个问题。我正在使用OpenXml将图像以及一些文本放在图像内容控件上。现在我很担心,它会从数据库中提取信息(所有信息似乎都很好)。现在,将图像和内容放在内容控件上是我遇到的主要问题。

我的代码看起来像是一种Web服务。

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Text = DocumentFormat.OpenXml.Wordprocessing.Text;

namespace eMemoSignatureService
{
    /// <summary>
    /// Summary description for signaturewebservice
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class signaturewebservice : System.Web.Services.WebService
    {
        string fullname;
        string designation;

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public bool PlaceSignatureonMsWord(string WEMAstaffID)
        {
            string constring = ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constring))
            {
                con.Open();
                string sqlq = "select * from [e-SignatureDB].[dbo].[signature_table] where staffID = @staffID";
                using (SqlCommand cmd = new SqlCommand(sqlq, con))
                {
                    cmd.Parameters.AddWithValue("@staffID", WEMAstaffID);
                    SqlDataReader rd = cmd.ExecuteReader();
                    if (rd.Read())
                    {
                        fullname = (rd["fullname"].ToString());
                        designation = (rd["designation"].ToString());
                        byte[] bytes = Convert.FromBase64String(rd["approval_signature"].ToString());
                        Image img;
                        using (MemoryStream ms = new MemoryStream(bytes))
                        {
                            img = Image.FromStream(ms);

                            string folderPath = Server.MapPath("~/Signature_image/");
                            string fileName =  fullname + ".jpg";
                            string imagePath = folderPath + fileName;
                            img.Save(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg);

                            using (WordprocessingDocument document = WordprocessingDocument.Open(@"C:\Users\emi\Desktop\e-Memo.docx", true))
                            {
                                MainDocumentPart mainPart = document.MainDocumentPart;
                                DocumentFormat.OpenXml.Wordprocessing.Text text = null;
                                DocumentFormat.OpenXml.Wordprocessing.Text text2 = null;
                                SdtContentBlock designationBlk = null;
                                SdtContentBlock fullnameblk = null;

                                List<SdtBlock> sdtList = mainPart.Document.Descendants<SdtBlock>().ToList();

                                foreach (SdtBlock sdt in sdtList)
                                {
                                    Console.WriteLine(sdt.SdtProperties.GetFirstChild<Tag>().Val.Value);
                                }

                                if (designation == "Manager")
                                {
                                   // SdtElement s1 = mainPart.Document.Body.Descendants<SdtElement>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "ManName1").Single();
                                   // SdtElement s2 = mainPart.Document.Body.Descendants<SdtElement>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "ManDesg1").Single();

                                    SdtBlock s1 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "ManName1").Single();
                                    SdtBlock s2 = mainPart.Document.Body.Descendants<SdtBlock>().Where(r => r.SdtProperties.GetFirstChild<Tag>().Val == "ManDesg1").Single();

                                    SdtElement s3 = mainPart.Document.Body.Descendants<SdtElement>().FirstOrDefault(r =>
                                    {
                                        SdtElement p = r.Elements<SdtElement>().FirstOrDefault();
                                        if (p != null)
                                        {
                                            Console.WriteLine("P is not null");
                                            // Is it a picture content control?
                                            SdtContentPicture pict =
                                                p.Elements<SdtContentPicture>().FirstOrDefault();
                                            if (pict != null) Console.WriteLine("Pict is not null");
                                            // Get the alias.
                                            SdtAlias a = p.Elements<SdtAlias>().FirstOrDefault();
                                            if (pict != null && a.Val == "Approval1")
                                                return true;
                                        }
                                        return false;
                                    });
                                    if (s1 != null)
                                    {
                                        fullnameblk = s1.Descendants<SdtContentBlock>().FirstOrDefault();
                                        text = fullnameblk.Descendants<Text>().FirstOrDefault();
                                        text.Text = fullname;
                                        Console.WriteLine(text.Text);
                                    }

                                    if (s2 != null)
                                    {
                                        designationBlk = s2.Descendants<SdtContentBlock>().FirstOrDefault();
                                        text2 = designationBlk.Descendants<Text>().FirstOrDefault();

                                        text2.Text = designation;
                                        Console.WriteLine(text2.Text);
                                    }

                                    string embed = null;
                                    if (s3 != null)
                                    {
                                        Drawing dr = s3.Descendants<Drawing>().FirstOrDefault();
                                        if (dr != null)
                                        {
                                            Blip blip = dr.Descendants<Blip>().FirstOrDefault();
                                            if (blip != null)
                                                embed = blip.Embed;
                                        }
                                    }

                                    if (embed != null)
                                    {
                                        IdPartPair idpp = document.MainDocumentPart.Parts
                                            .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                                        if (idpp != null)
                                        {
                                            ImagePart ip = (ImagePart)idpp.OpenXmlPart;
                                            using (FileStream fileStream =
                                                File.Open(imagePath, FileMode.Open))
                                                ip.FeedData(fileStream);
                                        }

                                        mainPart.Document.Save();
                                        document.Close();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
    }
}

现在我担心它会在此区域显示错误

                            if (s1 != null)
                            {
                                fullnameblk = s1.Descendants<SdtContentBlock>().FirstOrDefault();
                                text = fullnameblk.Descendants<Text>().FirstOrDefault();
                                text.Text = fullname;
                                Console.WriteLine(text.Text);
                            }

当我已经从SQL服务器获得数据时。我似乎缺少什么?

1 个答案:

答案 0 :(得分:0)

该区域存在一些导致您“担忧”的问题(请参见代码注释):

// Since you use the Single() method in setting s1, s1 can't be null.
// Otherwise, you would have had an exception already before reaching
// the following if statement.
if (s1 != null)
{
    // You could simply say s1.SdtContentBlock.
    fullnameblk = s1.Descendants<SdtContentBlock>().FirstOrDefault();

    // fullnameblk can theoretically be null and you don't check for that.
    // However, unless you have an edge case, this should not be an issue.
    text = fullnameblk.Descendants<Text>().FirstOrDefault();

    // text can be null (e.g., in an empty paragraph) and you don't check for that.
    // This can happen in practice and is not even an edge case.
    text.Text = fullname;

    Console.WriteLine(text.Text);
}

因此,如果您在System.NullReferenceException上获得text.Text,这是因为您的SdtContentBlockw:sdtContent)没有任何Text({{1} })后代。如果w:t不包含任何SdtContentBlockParagraph)或仅包含一个空的w:p,则会发生这种情况。