0

我一直在我的网站上工作,并尝试创建一个导出到 Word。导出效果很好,将 HTML 字符串转换为 DOCX。

我试图弄清楚如何调整行距。默认情况下,Word 在之后添加 8pt 间距并将行间距设置为双倍。我更喜欢 0 和 Single。

这是我为保存 Word 文档而创建的函数:

private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
    string htmlSectionID = "Sect1";
    //Creating a word document using the the Open XML SDK 2.0
    WordprocessingDocument document = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document);

    //create a paragraph
    MainDocumentPart mainDocumenPart = document.AddMainDocumentPart();
    mainDocumenPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
    Body documentBody = new Body();
    mainDocumenPart.Document.Append(documentBody);


    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));

    // Create alternative format import part.
    AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);

    //ms.Seek(0, SeekOrigin.Begin);

    // Feed HTML data into format import part (chunk).
    formatImportPart.FeedData(ms);
    AltChunk altChunk = new AltChunk();
    altChunk.Id = htmlSectionID;

    mainDocumenPart.Document.Body.Append(altChunk);

    /*
     inch equiv = 1440 (1 inch margin)
     */
    double width = 8.5 * 1440;
    double height = 11 * 1440;

    SectionProperties sectionProps = new SectionProperties();
    PageSize pageSize;
    if (isLandScape)
    {
        pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
    }
    else
    {
        pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };
    }

    rMargin = rMargin * 1440;
    lMargin = lMargin * 1440;
    bMargin = bMargin * 1440;
    tMargin = tMargin * 1440;

    PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };

    sectionProps.Append(pageSize);
    sectionProps.Append(pageMargin);
    mainDocumenPart.Document.Body.Append(sectionProps);

    //Saving/Disposing of the created word Document
    document.MainDocumentPart.Document.Save();
    document.Dispose();
}

在搜索中,我发现了这段代码:

SpacingBetweenLines spacing = new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" };

我已经在我的函数中放置了很多地方,但我似乎找不到正确的地方来追加这个设置。

4

2 回答 2

4

我致力于尝试在代码中设置间距的功能,但无法删除间距。我决定尝试创建一个模板 Word 文档并在该文档中设置间距。

我复制 template.docx 文件,创建我将使用的文件,然后使用以下调整后的函数添加 HTML 字符串:

private static void SaveDOCX(string fileName, string BodyText, bool isLandScape, double rMargin, double lMargin, double bMargin, double tMargin)
{
    WordprocessingDocument document = WordprocessingDocument.Open(fileName, true);
    MainDocumentPart mainDocumenPart = document.MainDocumentPart;

    //Place the HTML String into a MemoryStream Object
    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes("<html><head></head><body>" + BodyText + "</body></html>"));

    //Assign an HTML Section for the String Text
    string htmlSectionID = "Sect1";

    // Create alternative format import part.
    AlternativeFormatImportPart formatImportPart = mainDocumenPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, htmlSectionID);

    // Feed HTML data into format import part (chunk).
    formatImportPart.FeedData(ms);
    AltChunk altChunk = new AltChunk();
    altChunk.Id = htmlSectionID;

    //Clear out the Document Body and Insert just the HTML string.  (This prevents an empty First Line)
    mainDocumenPart.Document.Body.RemoveAllChildren();
    mainDocumenPart.Document.Body.Append(altChunk);

    /*
     Set the Page Orientation and Margins Based on Page Size
     inch equiv = 1440 (1 inch margin)
     */
    double width = 8.5 * 1440;
    double height = 11 * 1440;

    SectionProperties sectionProps = new SectionProperties();
    PageSize pageSize;
    if (isLandScape)
        pageSize = new PageSize() { Width = (UInt32Value)height, Height = (UInt32Value)width, Orient = PageOrientationValues.Landscape };
    else
        pageSize = new PageSize() { Width = (UInt32Value)width, Height = (UInt32Value)height, Orient = PageOrientationValues.Portrait };

    rMargin = rMargin * 1440;
    lMargin = lMargin * 1440;
    bMargin = bMargin * 1440;
    tMargin = tMargin * 1440;

    PageMargin pageMargin = new PageMargin() { Top = (Int32)tMargin, Right = (UInt32Value)rMargin, Bottom = (Int32)bMargin, Left = (UInt32Value)lMargin, Header = (UInt32Value)360U, Footer = (UInt32Value)360U, Gutter = (UInt32Value)0U };

    sectionProps.Append(pageSize);
    sectionProps.Append(pageMargin);
    mainDocumenPart.Document.Body.Append(sectionProps);

    //Saving/Disposing of the created word Document
    document.MainDocumentPart.Document.Save();
    document.Dispose();
}

通过使用模板文件,行距是正确的。

对于那些可能发现此函数有用的人,这里是调用该函数的代码:

string filePath = "~/Content/Exports/Temp/";

string WordTemplateFile = HttpContext.Current.Server.MapPath("/Content/Templates/WordTemplate.docx");
string DestinationPath = HttpContext.Current.Server.MapPath(filePath);
string NewFileName = DOCXFileName + ".docx";

string destFile = System.IO.Path.Combine(DestinationPath, NewFileName);

System.IO.File.Copy(WordTemplateFile, destFile, true);

SaveDOCX(destFile, HTMLString, isLandScape, rMargin, lMargin, bMargin, tMargin);
于 2014-01-05T19:58:36.473 回答
0

您无法更改格式,因为您的代码只是将 HTML 插入 Word 文档。要更改格式,需要将 HTML 文本转换为常规文本并将其添加到 Word 文档中。我遇到了类似的问题,使用 HtmlToOpenXml 库使这变得快速而简单。

using HtmlToOpenXml;

然后是函数:

    protected virtual void createWord()
    {
        string html = "*myHtml*";

        // Create WordProcessingDocument
        WordprocessingDocument doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
        MainDocumentPart mainPart = doc.MainDocumentPart;
        if (mainPart == null)
            mainPart = doc.AddMainDocumentPart();

        Document document = doc.MainDocumentPart.Document;
        if (document == null)
            document = mainPart.Document = new Document();

        Body body = mainPart.Document.Body;
        if (body == null)
            body = mainPart.Document.Body = new Body(new SectionProperties(new PageMargin() { Top = 1440, Right = 1440U, Bottom = 1440, Left = 1440U, Header = 720U, Footer = 720U, Gutter = 0U }));

        // Convert Html to OpenXml
        HtmlConverter converter = new HtmlConverter(mainPart);
        converter.ParseHtml(html);

        // Reformat paragraphs
        ParagraphProperties pProps = new ParagraphProperties(new SpacingBetweenLines() { Line = "240", LineRule = LineSpacingRuleValues.Auto, Before = "0", After = "0" });
        var paragraphs = doc.MainDocumentPart.Document.Body.Descendants<Paragraph>().ToList();
        foreach (Paragraph p in paragraphs)
        {
            if (p != null)
                p.PrependChild(pProps.CloneNode(true));
        }

        // Close the document handle
        doc.Close();
    }
于 2021-06-07T13:58:38.540 回答