byte[] byteArray = File.ReadAllBytes("C:\\test.docm");
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
//OpenXML bookmarks
using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
{
#region " 处理正文的bookmark"
foreach (BookmarkStart bookmark in doc.MainDocumentPart.RootElement.Descendants<BookmarkStart>())
{
for (int i = 0; i < mapBookmarks.Length; i++)
{
System.Data.DataTable dt = buliDS.Tables[mapBookmarks[i].TableName];
if (mapBookmarks[i].BookmarkName == bookmark.Name)
{
var option = mapBookmarks[i];
Run bkText = bookmark.NextSibling<Run>();
DocumentFormat.OpenXml.OpenXmlElement elem = bookmark.NextSibling();
#region replace values
switch (option.Type)
{
case BookmarkType.None:
break;
case BookmarkType.Value:
string val = "";
switch (option.Source)
{
case DataSource.None:
break;
case DataSource.Public:
//数据从界面输入
try
{
val = publdic[mapBookmarks[i].Key].ToString();
}
catch (Exception ex)
{
val = "";
}
bkText.GetFirstChild<Text>().Text = val;
break;
case DataSource.Confirmation:
if (mapBookmarks[i].TableName != null)
{
try
{
//数据从数据源中拿
//buliDS.Tables[mapBookmarks[i].TableName] 拿到对应的表。Rows[0][mapBookmarks[i].Key] 拿到实际对应key的数据
string tabName = mapBookmarks[i].TableName;
if (dt.Rows.Count > 0)
{
//确定当前操作的是那一条confromation数据(下面一句,不懂请查看datatable的select方法)
DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + " = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);
if (dr.Length > 0)
{
try
{
val = dr[0][mapBookmarks[i].Key].ToString();
}
catch (Exception ex)
{
val = "";
}
}
}
bkText.GetFirstChild<Text>().Text = val;
}
catch (Exception ex)
{
Console.WriteLine("Confirmation:" + ex);
}
}
break;
default:
break;
}
elem = elem.NextSibling();
while (elem != null && !(elem is BookmarkEnd))
{
DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
break;
case BookmarkType.Table:
string tableName = mapBookmarks[i].TableName;
if (mapBookmarks[i].TableName != null)
{
try
{
if (bookmark.Name == "其他事项")
{
try
{
string valStr = "";
DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + " = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);
for (int rowIndex = 0; rowIndex < dr.Length; rowIndex++)
{
foreach (var item1 in mapBookmarks[i].TableDataFormat)
{
try
{
valStr += dr[rowIndex][item1.Key].ToString() + " ";
}
catch (Exception ex)
{
valStr += "";
}
}
}
bookmark.Parent.Parent.ReplaceChild(new Paragraph(new Run(new Text(valStr))), bookmark.Parent);
}
catch (Exception ex)
{
logger.Error(string.Format("其他事项(SpeedProgress) 异常. ex:{0}", ex));
}
}
else
{
int index = 0;
foreach (var item in bookmark.Parent.Parent.ChildElements)
{
if (item.LocalName == "tbl")
{
try
{
if (bookmark.Parent.Parent.ElementAt(index + 1).InnerText == ("@" + bookmark.Name))
{
if (dt.Rows.Count > 0)
{
DataRow[] dr = dt.Select(ShellForm.columnsName.BatchNo_Key + " = " + batchNo + " AND " + ShellForm.columnsName.SeqNo_Key + " = " + seqNo);
if (dr.Length > 0)
{
//if (dt.Rows.Count > 0)
//{
for (int rowIndex = 0; rowIndex < dr.Length; rowIndex++)
{
筛选和当前batchno和seqno对应的数据
//string dtKey = dt.Rows[rowIndex][ShellForm.columnsName.BatchNo_Key].ToString() + dt.Rows[rowIndex][ShellForm.columnsName.SeqNo_Key].ToString();
locKey 为选中数据时,对应模板和batchno和seq的对应的key
//if (dtKey == locKey)
//{
TableRow tr = new TableRow();
int tcIndex = 1;
foreach (var item1 in mapBookmarks[i].TableDataFormat)
{
// Create a cell.
TableCell tc1 = new TableCell();
//Properties
RunProperties runProperty = new RunProperties();
RunFonts runFont = new RunFonts();
runFont.Ascii = "Verdana";
runFont.HighAnsi = "Verdana";
runFont.EastAsia = "华文细黑";
FontSize newSize = new FontSize();
newSize.Val = "16";
ParagraphProperties paragraphProperty = new ParagraphProperties(new Justification() { Val = JustificationValues.Center });
paragraphProperty.KeepNext = new KeepNext();
paragraphProperty.KeepLines = new KeepLines();
runProperty.Append(runFont);
runProperty.Append(newSize);
// Run
Run newRun = new Run();
newRun.Append(runProperty);
newRun.Append(new Text(dr[rowIndex][item1.Key].ToString()));
// Specify the table cell content.
tc1.Append(paragraphProperty);
tc1.Append(new Paragraph(newRun));
tc1.TableCellProperties = ((item.LastChild as TableRow).ChildElements[tcIndex] as TableCell).TableCellProperties.Clone() as TableCellProperties;
// Append the table cell to the table row.
tr.Append(tc1);
tcIndex++;
}
tr.TableRowProperties = new TableRowProperties();
item.Append(tr);
}
//}
// }
}
else
{
AddBlankRows(item, mapBookmarks, i);
}
}
else
{
AddBlankRows(item, mapBookmarks, i);
}
}
}
catch (Exception ex)
{
logger.Error(string.Format("tbl(SpeedProgress). ex:{0}", ex));
}
}
index++;
}
}
}
catch (Exception ex)
{
Console.WriteLine("Table:" + ex);
logger.Error(string.Format("Table. BatchNo:{0} SeqNo:{1}. ex:{2}", batchNo, seqNo, ex));
}
}
while (elem != null && !(elem is BookmarkEnd))
{
DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
break;
case BookmarkType.Barcode:
try
{
string BarcodePath = "";
BarcodePath = BulidBarCode(buliDS.Tables[ShellForm.columnsName.CSR], BulidTempList[locKey]);
MainDocumentPart BarcodePart = doc.MainDocumentPart;
ImagePart BarcodeImagePart = BarcodePart.AddImagePart(ImagePartType.Png);
using (FileStream BarcodeStream = new FileStream(BarcodePath, FileMode.Open))
{
BarcodeImagePart.FeedData(BarcodeStream);
}
var BarcodeElement = ImageElement(doc.MainDocumentPart.GetIdOfPart(BarcodeImagePart), 1300000, 590000);
bookmark.Parent.Parent.ReplaceChild(new Paragraph(BarcodeElement), bookmark.Parent);
while (elem != null && !(elem is BookmarkEnd))
{
DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
}
catch (Exception ex)
{
ShowingProcessMsg(string.Format("异常:Barcode;exMessage:{0}\n", ex.Message));
}
break;
case BookmarkType.QRcode:
try
{
string QRcodePath = "";
QRcodePath = BulidQRCode(buliDS.Tables[ShellForm.columnsName.CSR], BulidTempList[locKey]);
MainDocumentPart QRcodePart = doc.MainDocumentPart;
ImagePart QRcodeImagePart = QRcodePart.AddImagePart(ImagePartType.Jpeg);
using (FileStream QRcodeStream = new FileStream(QRcodePath, FileMode.Open))
{
QRcodeImagePart.FeedData(QRcodeStream);
}
var QRcodeElement = ImageElement(doc.MainDocumentPart.GetIdOfPart(QRcodeImagePart), 800000, 800000);
// add the image element to body, the element should be in a Run.
//bookmark.Parent.InsertAfter<Run>(new Run(QRcodeElement), bookmark);
//bookmark.Parent.InsertBefore<Run>(new Run(QRcodeElement), bookmark);
//doc.MainDocumentPart.Document.Body.InsertBefore<Run>(new Run (QRcodeElement),bookmark);
//doc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(QRcodeElement)));
bookmark.Parent.Parent.ReplaceChild(new Paragraph(QRcodeElement), bookmark.Parent);
while (elem != null && !(elem is BookmarkEnd))
{
DocumentFormat.OpenXml.OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
}
catch (Exception ex)
{
ShowingProcessMsg(string.Format("异常:QRcode;exMessage:{0}\n", ex.Message));
}
break;
default:
break;
}
#endregion
break;
}
}
}
#endregion
doc.Close();
}
File.WriteAllBytes(tempFileName, stream.ToArray());
}