我正在使用 OpenXML 操作一个 word 文档,并且我在该文档中有一个字段来设置日期。但问题是当我插入像 2012 年 1 月 10 日这样的日期时,它会在 2012 年 10 月 10 日星期一打印在文档中。这不是我想要的。我希望它像 2012 年 1 月 10 日一样。我怎样才能做到这一点?
@Hans @skynorth 这是我正在使用的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace Inbay_Debrief_Report_Sender
{
class InsertDetailsProgram
{
public static bool InsertDetals(string[] ObservationsValues, string[] ActiontakenValues, string[] ReccomendationsValues)
{
// convert template to document
TemplateToDocument("DebriefReportTemplate.dotx", "DebriefReportTemplate.docx");
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open("DebriefReportTemplate.docx", true))
{
List<SdtRun> sdtBlocks = new List<SdtRun>();
sdtBlocks.AddRange(wordDoc.MainDocumentPart.Document.Body.ChildElements.OfType<SdtRun>());
foreach (Paragraph para in wordDoc.MainDocumentPart.Document.Body.OfType<Paragraph>())
{
var moreBlocks = para.ChildElements.OfType<SdtRun>();
if (moreBlocks != null && moreBlocks.Count() > 0)
sdtBlocks.AddRange(moreBlocks);
}
foreach (SdtRun block in sdtBlocks)
{
if (block.SdtProperties != null)
{
Tag tag = block.SdtProperties.ChildElements.OfType<Tag>().ElementAt(0);
switch (tag.Val.Value)
{
case "caseTag":
block.ModifyContent(Variables.CaseNumber);
break;
case "nameTag":
block.ModifyContent(Variables.CustomerName);
break;
case "typeTag":
block.ModifyContent(Variables.MachineType);
break;
case "dateTag":
block.ModifyContent(Variables.ReportedDate); // this is where i insert the date
break;
case "engineerTag":
block.ModifyContent(Variables.EngineerName);
break;
case "virusTag":
if (Variables.virus == true) { block.Check(); }
else { block.UnCheck(); }
break;
case "diagnosticTag":
if (Variables.Diagnostic == true) { block.Check(); }
else { block.UnCheck(); }
break;
case "osupgradeTag":
if (Variables.OSUpgrade == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "backupTag":
if (Variables.DataBackup == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "datarecoveryTag":
if (Variables.DataRecovery == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "softwareTag":
if (Variables.SoftwareInstallation == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "datacleanseTag":
if (Variables.DataCleanse == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "gadgetTag":
if (Variables.GadgetInstallation == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "computersetTag":
if (Variables.DataBackup == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "parentalTag":
if (Variables.ParentalControl == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "smartphoneTag":
if (Variables.SmartPhone == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "factoryresetTag":
if (Variables.FactoryReset == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "emailsetupTag":
if (Variables.Email == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "networkingTag":
if (Variables.Networking == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "tuneupTag":
if (Variables.Tuneup == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "broadbandTag":
if (Variables.Broadband == true)
{ block.Check(); }
else
{ block.UnCheck(); }
break;
case "observationsArea":
List<string> dynamicList = new List<string>(ObservationsValues);
List<Paragraph> newChildren = CreateNewChildren(dynamicList);
Paragraph oldChild = block.Parent as Paragraph;
oldChild.ParagraphProperties.SpacingBetweenLines.After = "0";
oldChild.ParagraphProperties.SpacingBetweenLines.Before = "0";
newChildren.ForEach(ch =>
{
oldChild = wordDoc.MainDocumentPart.Document.Body.InsertAfter(ch, oldChild);
});
break;
case "actionsTakenArea":
List<string> dynamicList1 = new List<string>(ActiontakenValues);
List<Paragraph> newChildren1 = CreateNewChildren(dynamicList1);
Paragraph oldChild1 = block.Parent as Paragraph;
var oldChildSibling = oldChild1.PreviousSibling() as Paragraph;
if (oldChildSibling.InnerText.Length == 0)
oldChildSibling.Remove();
oldChild1.ParagraphProperties.SpacingBetweenLines.After = "0";
oldChild1.ParagraphProperties.SpacingBetweenLines.Before = "0";
// now if you want some space, change the values of After & Before
newChildren1.ForEach(ch =>
{
oldChild1 = wordDoc.MainDocumentPart.Document.Body.InsertAfter(ch, oldChild1);
});
break;
case "reccomendationsArea":
List<string> dynamicList2 = new List<string>(ReccomendationsValues);
List<Paragraph> newChildren2 = CreateNewChildren(dynamicList2);
Paragraph oldChild2 = block.Parent as Paragraph;
var oldChildSibling1 = oldChild2.PreviousSibling() as Paragraph;
if (oldChildSibling1.InnerText.Length == 0)
oldChildSibling1.Remove();
oldChild2.ParagraphProperties.SpacingBetweenLines.After = "0";
oldChild2.ParagraphProperties.SpacingBetweenLines.Before = "0";
// now if you want some space, change the values of After & Before
newChildren2.ForEach(ch =>
{
oldChild2 = wordDoc.MainDocumentPart.Document.Body.InsertAfter(ch, oldChild2);
});
break;
}
}
}
// save the document
wordDoc.MainDocumentPart.Document.Save();
}
return true;
}
private static List<Paragraph> CreateNewChildren(List<string> dynamicList)
{
List<Paragraph> newParaCollection = new List<Paragraph>();
dynamicList.ForEach(item =>
{
Paragraph paragraph = new Paragraph() { RsidParagraphMarkRevision = "008C2139", RsidParagraphAddition = "008C2139", RsidParagraphProperties = "00050C00", RsidRunAdditionDefault = "008C2139" };
ParagraphProperties paragraphProperties1 = new ParagraphProperties() { SpacingBetweenLines = new SpacingBetweenLines() { After = "0", Before = "0" } };
ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId() { Val = "ListParagraph" };
NumberingProperties numberingProperties1 = new NumberingProperties();
NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference() { Val = 0 };
NumberingId numberingId1 = new NumberingId() { Val = 1 };
numberingProperties1.Append(numberingLevelReference1);
numberingProperties1.Append(numberingId1);
ParagraphBorders paragraphBorders1 = new ParagraphBorders();
TopBorder topBorder1 = new TopBorder() { Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)6U, Space = (UInt32Value)1U };
BottomBorder bottomBorder1 = new BottomBorder() { Val = BorderValues.Single, Color = "auto", Size = (UInt32Value)6U, Space = (UInt32Value)1U };
// paragraphBorders1.Append(topBorder1);
// paragraphBorders1.Append(bottomBorder1);
ParagraphMarkRunProperties paragraphMarkRunProperties1 = new ParagraphMarkRunProperties();
RunStyle runStyle1 = new RunStyle() { Val = "Style1" };
FontSize fontSize1 = new FontSize() { Val = "29.5" };
paragraphMarkRunProperties1.Append(runStyle1);
paragraphMarkRunProperties1.Append(fontSize1);
paragraphProperties1.Append(paragraphStyleId1);
paragraphProperties1.Append(numberingProperties1);
//if (dynamicList.IndexOf(item) == dynamicList.Count - 1)
//{
// paragraphProperties1.Append(paragraphBorders1);
//}
paragraphProperties1.Append(paragraphMarkRunProperties1);
Run run1 = new Run();
RunProperties runProperties1 = new RunProperties();
RunStyle runStyle2 = new RunStyle() { Val = "Style1" };
FontSize fontSize2 = new FontSize() { Val = "29.5" };
FontSizeComplexScript fontSizeComplexScript1 = new FontSizeComplexScript() { Val = "18" };
Bold BoldObj = new Bold() { Val = false };
runProperties1.Append(runStyle2);
runProperties1.Append(fontSize2);
runProperties1.Append(BoldObj);
runProperties1.Append(fontSizeComplexScript1);
Text text1 = new Text();
text1.Text = item;
run1.Append(runProperties1);
run1.Append(text1);
paragraph.Append(paragraphProperties1);
paragraph.Append(run1);
newParaCollection.Add(paragraph);
});
return newParaCollection;
}
private static void TemplateToDocument(string templateFile, string documentFile)
{
MemoryStream presentationStream = null;
using (Stream tplStream = File.Open(templateFile, FileMode.Open, FileAccess.Read))
{
presentationStream = new MemoryStream((int)tplStream.Length);
tplStream.Copy(presentationStream);
presentationStream.Position = 0L;
}
using (WordprocessingDocument wordPackage = WordprocessingDocument.Open(presentationStream, true))
{
wordPackage.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart docPart = wordPackage.MainDocumentPart;
docPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate",
new Uri(templateFile, UriKind.RelativeOrAbsolute));
docPart.Document.Save();
}
File.WriteAllBytes(documentFile, presentationStream.ToArray());
}
}
public static class Extensions
{
public static void Copy(this Stream source, Stream target)
{
if (source != null)
{
MemoryStream mstream = source as MemoryStream;
if (mstream != null) mstream.WriteTo(target);
else
{
byte[] buffer = new byte[2048];
int length = buffer.Length, size;
while ((size = source.Read(buffer, 0, length)) != 0)
target.Write(buffer, 0, size);
}
}
}
public static void ModifyContent(this SdtRun block, string content)
{
SdtContentRun contentBlock = block.ChildElements.OfType<SdtContentRun>().ElementAt(0);
Run run = contentBlock.ChildElements.OfType<Run>().ElementAt(0);
if (run != null)
{
Text text = run.GetFirstChild<Text>();
text.Text = content;
}
}
public static void Check(this SdtRun block)
{
DocumentFormat.OpenXml.Office2010.Word.SdtContentCheckBox chkBox = block.SdtProperties.GetFirstChild<DocumentFormat.OpenXml.Office2010.Word.SdtContentCheckBox>();
chkBox.Checked.Val = DocumentFormat.OpenXml.Office2010.Word.OnOffValues.One;
block.ModifyContent("☒");
}
public static void UnCheck(this SdtRun block)
{
DocumentFormat.OpenXml.Office2010.Word.SdtContentCheckBox chkBox = block.SdtProperties.GetFirstChild<DocumentFormat.OpenXml.Office2010.Word.SdtContentCheckBox>();
chkBox.Checked.Val = DocumentFormat.OpenXml.Office2010.Word.OnOffValues.Zero;
block.ModifyContent("☐");
}
}
}