/// <summary> /// 应用表格模板 /// </summary> /// <param name="tableContent"></param> /// <param name="tableTemplate"></param> /// <param name="colNames"></param> private void ApplyToTableTemplate(XWPFTable tableContent, TableTemplateModel tableTemplate, Dictionary <int, string> colNames) { int startRowNum = tableTemplate.StartRowNumber; for (var rowIndex = 0; rowIndex < tableTemplate.Value.Rows.Count; rowIndex++) { int documentRowIndex = rowIndex + startRowNum; XWPFTableRow row = rowIndex == 0 ? tableContent.GetRow(documentRowIndex) : tableContent.InsertNewTableRow(documentRowIndex - 1); int cellCount = row.GetTableCells().Count; int count = colNames.Max(m => m.Key); for (int i = cellCount - 1; i < count; i++) { row.CreateCell(); } foreach (KeyValuePair <int, string> colName in colNames) { string[] colValues = colName.Value.Split(','); string value = tableTemplate.Value.Rows[rowIndex][colValues[0]].ToString(); XWPFParagraph paragraph = GetCellContent(rowIndex, colName.Key, tableContent, value, tableTemplate.OnSetCellText); XWPFTableCell cell = row.GetCell(colName.Key); cell.SetParagraph(paragraph); for (var i = 1; i < colValues.Length; i++) { ApplyCommand(colValues[i], colName.Key, row); } } } }
/// <summary> /// 应用表格模板 /// </summary> /// <param name="document"></param> /// <param name="tableTemplates"></param> /// <param name="stringTemplates"></param> private void ApplyToTableTemplate(IBody document, IReadOnlyCollection <TableTemplateModel> tableTemplates, IReadOnlyCollection <StringTemplateModel> stringTemplates) { foreach (XWPFTable tableContent in document.Tables) { if (tableTemplates.Count > 0) { for (var rowIndex = 0; rowIndex < tableContent.NumberOfRows; rowIndex++) { (string tableName, Dictionary <int, string> colNames) = GetTableNameAndColName(tableContent, rowIndex); if (string.IsNullOrEmpty(tableName)) { continue; } TableTemplateModel tableTemplate = tableTemplates.FirstOrDefault(m => m.Key == tableName); if (tableTemplate == null) { continue; } ApplyToTableTemplate(tableContent, tableTemplate, colNames); break; } } ApplyTableToStringTemplate(tableContent, stringTemplates); } }